content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division from __future__ import unicode_literals import logging import tensorflow as tf class AutoEncoder: """ Autoencoder implemented with tensorflow """ def __init__(self, encoder_dims, decoder_dims=None, lr=1e-0...
import pandas as pd import argparse from imblearn.over_sampling import SVMSMOTE import numpy as np import os import shutil import argparse import json from json_manager import JsonManager import pipeline_constants as constants def process_command_line_args(): ap = argparse.ArgumentParser() ap.add_argument("-c", "--c...
from subprocess import call import time import os import selenium from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from config import EMAIL def click_op...
from __future__ import absolute_import import pytest import numpy as np from astropy import units as u from astropy.coordinates import Longitude, Latitude, Angle from sunpy.physics.transforms.differential_rotation import diff_rot, _sun_pos, _calc_P_B0_SD, rot_hpc from sunpy.tests.helpers import assert_quantity_allclose...
import sys import os import pytest root_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) if root_path not in sys.path: sys.path.append(root_path) from common import base # common_path = os.path.join(os.getcwd(), r'../../common') # # print(common_path) # if common_path not in sys.path: # s...
import torch from typing import Union, Optional from colossalai.tensor import ColoTensor GeneralTensor = Union[ColoTensor, torch.Tensor] Number = Union[int, float] def convert_to_colo_tensor(tensor: Optional[GeneralTensor]) -> Optional[ColoTensor]: if tensor is not None and not isinstance(tensor, ColoTensor): ...
# pyskel import time from random import random has_legs = False class Simulation(object): def __init__(self, pars): self.pars = pars self.pd = None def mod_run(sim, p): _, p2 = sim.pars sim.pars = p, p2 return run(sim) def run(sim): pd = [] p1, p2 = sim.pars for ctr in...
import numpy as np import pytest from alitra import AlignFrames, Euler, FrameTransform, PointList, Translation @pytest.mark.parametrize( "eul_rot, ref_translations, p_robot,rotation_axes", [ ( Euler(psi=np.pi * -0.0, from_="robot", to_="asset"), Translation(x=200030, y=10000, ...
# Copyright (C) 2018 Hatching B.V. # This file is licensed under the MIT License, see also LICENSE. import base64 import datetime import logging import os.path import yaml from arbiter.const import MINIMUM_STAKE_DEFAULT log = logging.getLogger(__name__) def repr_timedelta(dumper, data): # Fun for days r = {...
from .sphere import Sphere
# -*- coding: utf-8 -*- """Uniform Resource Identifier .. seealso:: :rfc:`3986` """ # TODO: parse HTTP/1.0-';'-params? import re from socket import AF_INET, AF_INET6, error as SocketError, inet_ntop, inet_pton from httoop.exceptions import InvalidURI from httoop.six import int2byte, iterbytes, with_metaclass from ht...
# coding=utf-8 #pylint:disable=no-name-in-module """ Module for video source acquisition. Classes capture data from a video source into a numpy array. """ import logging import datetime import cv2 import numpy as np import sksurgerycore.utilities.validate_file as vf import sksurgeryimage.utilities.camera_utilities as...
from __future__ import absolute_import from __future__ import print_function from __future__ import division import functools import math import numpy as np from collections import OrderedDict import veriloggen as vg import nngen.basic_types as bt import nngen.util as util class slice_(bt._Operator): """ C...
# before changing tasks, task, activity_type to task from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView from django.views.generic import TemplateView from django import forms from avs.models import * from avs.forms import * from django.shortc...
# coding: utf-8 import unittest from getsub.util import extract_name class TestExtractName(unittest.TestCase): def test_all_en(self): name = "Young.Sheldon.S01.1080p.WEB-DL.DD5.1.H.264-YFN[v].rar" new_name = extract_name(name) self.assertEqual(new_name, name) def test_mixed(self): ...
#!/usr/bin/env python # Use joystick input to launch behavioral nodes in jackal # # Intro to Robotics - EE5531 - Spring 2018 # Final Project # # Group #1 # Narendra # Alex # Shivam # # version: v1.5 # define imports import rospy import roslaunch import sys imp...
#!/usr/bin/python """ Test the function that maps from EOS """ import numpy as np import pylab as P import scipy.integrate import scipy.interpolate import radiofisher as rf from radiofisher.experiments import cosmo C = 3e5 ax1 = P.subplot(111) def old_eos_fisher_matrix_derivs(cosmo, cosmo_fns): """ Pre-calc...
import pyparsing as _pp def _swap_infix(s, l, t): t[0][0], t[0][1] = t[0][1], t[0][0] _quoted = _pp.QuotedString('"', escChar='\\') _plain_tag = _pp.Word(_pp.alphas + "_", _pp.alphanums + "_-") _tag = (_quoted | _plain_tag).setParseAction(lambda s, l, t: [['$', t[0]]]) _const = _pp.Word('01', exact=1).setParseA...
# Generated by Django 2.2.6 on 2019-10-14 20:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('backend', '0007_connection_guacdserver'), ] operations = [ migrations.AddField( model_name='con...
#!/usr/bin/env python -u """py65mon -- interact with a simulated 6502-based system Usage: %s [options] Options: -h, --help : Show this message -m, --mpu <device> : Choose which MPU device (default is 6502) -l, --load <file> : Load a file at address 0 -r, --rom <file> : Load a rom at the to...
import asyncio import multiprocessing import queue import sys import time import pytest from aplex.executor import (SubmitItem, HandlerCommands, WorkStates, WorkerStates) from aplex.process import _ProcessWorker from aplex.thread import _ThreadWorker @pytest.fixture(sco...
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Package for analyzing elastic tensors and properties. """ from .elastic import * # noqa from .strain import * # noqa from .stress import * # noqa
import time from requests import request, ConnectionError from ..utils import SSLHttpAdapter, module_member, parse_qs, user_agent from ..exceptions import AuthFailed class BaseAuth: """A authentication backend that authenticates the user based on the provider response""" name = '' # provider name, it's...
#! /usr/bin/env python # --coding:utf-8-- # coding: utf-8 # ━━━━━━神兽出没━━━━━━ #    ┏┓   ┏┓ #   ┏┛┻━━━┛┻┓ #   ┃       ┃ #   ┃   ━   ┃ #   ┃ ┳┛ ┗┳ ┃ #   ┃       ┃ #   ┃   ┻   ┃ #   ┃       ┃ #   ┗━┓   ┏━┛ #     ┃   ┃神兽保佑, 永无BUG! #     ┃   ┃Code is far away from bug with the animal protecting #     ┃   ┗━━━┓ # ...
from abc import abstractmethod from typing import Dict, Tuple from federate_learning.common.parameters import NDArrayList from federate_learning.common.metrics import Metrics from federate_learning.orchestrator.control_strategy import ControlStrategy class Model: def __init__(self, name: str, ...
from django.contrib import admin from apps.commons import models as commons_models from import_export.admin import ImportExportModelAdmin class OwnershipTypeAdmin(ImportExportModelAdmin): search_fields = ("name",) admin.site.register(commons_models.OwnershipType, OwnershipTypeAdmin)
"""Tests for logger: model User.""" from django.test import TestCase from geokey.core.models import LoggerHistory from geokey.users.tests.model_factories import UserFactory class LogUserTest(TestCase): """Test model User.""" def setUp(self): """Set up test.""" self.user = UserFactory.create...
"""Tests runner module.""" import os import random import time import uuid import webbrowser from collections import OrderedDict from schema import Schema, Or, Use from testplan import defaults from testplan.common.config import ConfigOption from testplan.common.entity import Entity, RunnableConfig, RunnableStatus,...
# Twowaits Twowaits Problem # Function to print words which can be created # using given set of characters def charCount(word): dict = {} for i in word: dict[i] = dict.get(i, 0) + 1 return dict def possible_words(lwords, charSet): for word in lwords: flag = 1 chars =...
import urllib.request,json from .models import Article,Source # Getting api key api_key = None # Getting the movie base url base_url = None # all_articles = api_key.get_everything(sort_by='source') def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.c...
from mne import events_from_annotations, annotations_from_events def transform_event_id(raw, transform_dic=None, description_transform=None): """Transform the description of Raw. Parameters ---------- raw : mne.Raw Raw instance. transform_dic : None | dic Dictionary hold...
from django.core.mail import EmailMessage from django.dispatch import receiver from django.template.loader import render_to_string from django.urls import reverse from django.conf import settings from django_rest_passwordreset.signals import reset_password_token_created @receiver(reset_password_token_created) def pas...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributions as D class SimpleNet(nn.Module): def __init__(self, s_dim, a_dim): super(SimpleNet, self).__init__() self.s_dim = s_dim self.a_dim = a_dim self.a1 = nn.Linear(s_dim, 100...
from setuptools import setup, find_packages setup( name="aiogh", version="0.0.1dev", packages=find_packages(), install_requires=["aiohttp", "aiohttp_session", "cryptography"], )
import numpy as np import yaml import sys import os import platform from pathlib import Path from setuptools import setup, find_packages from pybind11.setup_helpers import Pybind11Extension, build_ext script_dir = Path(os.path.abspath(os.path.dirname(__file__))) with open(script_dir / 'environment.yml') as f: requi...
############################### # - Set the fileToAverage name: fileToAverage = "SetTheFileName.txt" ############################### entriesToAverage = input("How much entries to average [int]?") outputFile = "ave_" + str(entriesToAverage) + "_" + fileToAverage current_list = open(fileToAverage, '...
import os import glob import numpy as np from sklearn.manifold import TSNE from sklearn.model_selection import cross_val_score from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt from pyLZJD import digest, sim #First, lets check if we have the t5 corpus if not (os.path.exists("t5-corp...
import json import logging import random import numpy as np import tflearn from django.conf import settings from django.utils import timezone from classifier.models import Sentence, Train, Category from classifier.utils import init_network, get_tokenized_words, get_categories, get_words logger = logging.getLogger(__...
from .mlp import MLP from .affine_transform import AffineTransform
import dash import dash_core_components as dcc import dash_html_components as html import plotly.express as px import pandas as pd import plotly.figure_factory as ff import numpy as np import pandas as pd import plotly.graph_objects as go import os import networkx as nx import matplotlib.pyplot as plt def plot_fig(no...
n, k = map(int, input().split()) numbers = map(int,input().split()) remainder_counts = [0] * k for number in numbers: remainder_counts[number % k] += 1 result = min(remainder_counts[0], 1) for i in range(1, k//2 + 1): if i != k - i: result += max( remainder_counts[i], remaind...
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import os import pandas as pd def main(txt_file, output_flag, check_all_frames, t_res, imgfmt, layer, no_stop): """Report if all the inputs OR outputs exist""" idx_table = {'video': 0, 'f-init': 1} df = pd.read_csv(txt_file, sep=...
import random def main(): print("Welcome to Hi-Low") the_number = random.randint(1, 100) guess = get_guess() while guess != the_number: if guess > the_number: print("Sorry, too high") elif guess < the_number: print("Sorry too low") guess = get_guess()...
import torch import torch.nn as nn import random class MeanPredictor(nn.Module): def __init__(self, data): super(MeanPredictor, self).__init__() self._throwaway_param = nn.Linear(1, 1) self.mean = sum(datum.y for datum in data.train) / float(len(data.train)) print('we gonna predict ...
"""Test the doctr-versions-menu CLI interface.""" import json import logging import platform import subprocess import sys from distutils.dir_util import copy_tree from pathlib import Path from click.testing import CliRunner from pkg_resources import parse_version import doctr_versions_menu from doctr_versions_menu.cl...
# body = {"email": "john@polyglot.ninja", "name": "John Smith", "id": 3} from flask import Flask from flask_restful import Resource, Api from flask_restful.reqparse import RequestParser app = Flask(__name__) api = Api(app, prefix="/api/v1") users = [ {"email": "masnun@gmail.com", "name": "Masnun", "id"...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pyotherside def read(path): try: with open(path, 'r') as f: read_data = f.read() pyotherside.send('log', "read file {0}".format(path)) return read_data except IOError: pyotherside.send('ioerror'...
import re import contextlib instance = None frontend = None RE_REVIEW_URL = re.compile(r"^remote:\s+http://.*/r/(\d+)\s*$") @contextlib.contextmanager def settings(user, settings, repository=None): data = { "settings": [{ "item": item, "value": value } for item, value in settings.items(...
# Generated by Django 2.2.10 on 2020-05-05 15:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('controlled_vocabulary', '0004_remove_controlledvocabulary_test'), ('core', '0025_resourcelanguage'), ] operations = [ migrations.AlterUniqu...
# -*- coding: utf-8 -*- #***************************************************************************** # Copyright (C) 2003-2006 Gary Bishop. # Copyright (C) 2006 Jorgen Stenarson. <jorgen.stenarson@bostream.nu> # # Distributed under the terms of the BSD License. The full license is in # the file COPYIN...
import unittest import torch import gpytorch from gpytorch.distributions import MultivariateNormal from gpytorch.lazy import CholLazyTensor, TriangularLazyTensor from gpytorch.variational import NaturalVariationalDistribution, TrilNaturalVariationalDistribution class Float64Test(unittest.TestCase): def setUp(se...
# -*- ################# # --------------------------------------------------------------------------- # Export_JSON_To_Shapefile.py # Created on: 2016-10-19 15:40:33.00000 # Usage: Export_JSON_To_Shapefile <Point_Input_JSON> <Line_Input_JSON> <Polygon_Input_JSON> # Description: # --------------------------------------...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # 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 th...
import base from sys import argv import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np import operator from collections import defaultdict THRESHOLD = 0.4 GRAPHFILE='per-char-analysis.png' if len(argv)!=2: print("Usage python h5_analyzer.py <db.h5>") exit(1) X, Y = base.H...
import unittest import numpy as np from itertools import product from apal import Khachaturyan from apal_cxx import PyKhachaturyan from apal_cxx import pytest_functional_derivative from apal_cxx import pytest_contract_tensors from apal_cxx import pytest_B_tensor_element from apal_cxx import pytest_strain_energy_sphere...
from django.contrib import admin from nano.badge.models import Badge class BadgeAdmin(admin.ModelAdmin): list_display = ('level', 'name', 'description') list_filter = ('level',) ordering = ('level', 'name',) admin.site.register(Badge, BadgeAdmin)
import pandas as pd #from datetime import datetime import numpy as np from mpl_toolkits.axes_grid1.inset_locator import inset_axes import matplotlib.pyplot as plt from scipy import interpolate # some processing stuff df = pd.read_excel( "data/cruise-arrivals.xlsx", dtype= {"YEAR":int, "ARRIVED DATE": str, "TIM...
from django.contrib import admin from .models import WikiArticleModel,WikiPermModel # Register your models here. # Wiki @admin.register(WikiArticleModel) class CustomGroupAdmin(admin.ModelAdmin): search_fields = ('title','level') @admin.register(WikiPermModel) class CustomGroupAdmin(admin.ModelAdmin): pass
import unittest import transaction import random from pyramid import testing from pyramid.response import Response import pytest from mood_bot.models import ( User, Sentiments, get_tm_session, ) from mood_bot.models.meta import Base from faker import Faker from passlib.apps import custom_app_context as co...
# Copyright 2018 Davide Spadini # # 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...
#!/usr/bin/env python """Tests for `deep_translator` package.""" import pytest from deep_translator import PonsTranslator, exceptions @pytest.fixture def pons(): return PonsTranslator(source="english", target="french") def test_content(pons): """Sample pytest test function with the pytest fixture as an a...
""" Copyright 2021, Institute e-Austria, Timisoara, Romania http://www.ieat.ro/ Developers: * Gabriel Iuhasz, iuhasz.gabriel@info.uvt.ro 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: htt...
import os import sys __version__ = "0.3.2" from .spectrum import Spectrum INSTDIR = os.path.join(sys.prefix, 'starfish_inst_data') __all__ = [ "constants", "emulator", "grid_tools", "models", "samplers", "spectrum", "Spectrum", "transforms", "utils", ]
import numpy as np import pandas as pd from scipy.special import expit from scipy.special import logit from scipy.stats import lognorm from itertools import product import sys from operator import mul from functools import reduce from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_proces...
import jax.numpy as jnp from jax import random import chex from jsl.experimental.seql.utils import classification_loss, regression_loss class SequentialDataEnvironment: def __init__(self, X_train: chex.Array, y_train: chex.Array, X_test: chex.Array, y...
import random from selenium.common.exceptions import NoSuchWindowException from selenium.webdriver.common.by import By from . import * URL = "https://web.vconf.garr.it/webapp/conference" logger = logging.getLogger(__name__) warnings.filterwarnings("ignore", category=UserWarning) def run(room='videodrone', y4m='./...
from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='gap_loader', version='0.3', description='Import hook for GAP files in SAGE math.', long_description=readme(), long_description_content_type='text/markdown', classifiers=[ ...
import re def nice_print(t): s = "" for l in t: s += "".join(l[250:]) + "\n" print(s) xmin = 108 - 1 w = 537-108+3 ymin = 3 h = 1913-3+1 clay = [["." for _ in range(w)] for _ in range(h)] while True: try: line = input() except: break # (x1, y1, x2, y2) a, b, c = map...
""" Various constants and utility functions for lexing """ import re from usfm_utils.usfm.tokens import Token UNESCAPED_FLAG_PREFIX = "$" FLAG_PREFIX = re.escape(UNESCAPED_FLAG_PREFIX) WHITESPACE = " \r\t\n" def make_flag(flag, boundary=True): """ A regex-compatible USFM flag :param str flag: flag of ...
#!/usr/bin/env python # encoding: utf-8 from distutils.core import setup setup(name='clock_puzzle_solver', description='Script for solving the "clock puzzle" mini-games present in the Final Fantasy XIII-2 role-playing game.', author='Thomas Nyman', author_email='thomas.nyman@cs.helsinki.fi', ur...
import sys import torch import random ID,FORM,LEMMA,UPOS,XPOS,FEATS,HEAD,DEPREL,DEPS,MISC=range(10) def read_conllu(inp,max_sent=0,drop_tokens=True,drop_nulls=True): comments=[] sent=[] yielded=0 for line in inp: line=line.strip() if line.startswith("#"): comments.append...
class _VolumeData(object): def __init__(self, size_x, size_y, size_z, delta_x, delta_y, delta_z): #byte array for speed. #if we later speed up array serializer #or make this an API, we should #convert to float [] self._data = [] s...
from os.path import join, dirname, isfile from PySide2.QtWidgets import QDialog, QMessageBox, QLayout from PySide2.QtCore import Qt, Signal from logging import getLogger from numpy import pi, array, array_equal from .....GUI.Dialog.DMatLib.DMatSetup.Gen_DMatSetup import Gen_DMatSetup from .....Classes.Material import ...
r=float(input('Digite o valor em reais que você possui na carteira: R$ ')) cot=4.85 d=(r/cot) print(' x.x '*25) print('Com o valor em sua carteira de R$ {} você pode comprar U$$ {:.2f}!'.format(r,d))
from utils.batchManagers import MultiNLIBatchManager, MRPCBatchManager, PDBBatchManager, SICKBatchManager, IBMBatchManager from math import sqrt import random random.seed(42) class MultiTaskTrainLoader(): """ Custom batch manager for multi-task learning. Iterating over this object yields a batch from one of the d...
import datetime n = int(input()) fmt = '%a %d %b %Y %H:%M:%S %z' for i in range(n): l = input() m = input() print(int(abs((datetime.datetime.strptime(l, fmt)-datetime.datetime.strptime(m, fmt)).total_seconds())))
# 284. Peeking Iterator # Given an Iterator class interface with methods: next() and hasNext(), # design and implement a PeekingIterator that support the peek() operation -- # it essentially peek() at the element that will be returned by the next call to next(). # Here is an example. # Assume that the iterator is ...
"""Implements the base crawler which all the rules are based on. Crawlers, crawl through the trees returned by the parser and evaluate particular rules. The intent is that it should be possible for the rules to be expressed as simply as possible, with as much of the complexity abstracted away. The evaluation functio...
import copy import re import unicodedata as ud from enum import Enum from WiktionaryTags import WiktionaryTags # State: Is the parser reading an etymology or a pronunciation entry? 0 if no, 1 if etymology, 2 if pronunciation class State(Enum): OTHER = 0 ETYM = 1 PRONOUNCE = 2 # Stores a si...
import os import pickle import requests from flask import Flask from datetime import datetime app = Flask(__name__) def send_notification(message): """Send push notification.""" pushover_token = os.getenv('PUSHOVER_TOKEN') pushover_url = 'https://api.pushover.net/1/messages.json' params = { '...
""" Simple example custom service, used to drive shell commands on a node. """ from typing import Tuple from core.nodes.base import CoreNode from core.services.coreservices import CoreService, ServiceMode class ExampleService(CoreService): """ Example Custom CORE Service :cvar name: name used as a uniqu...
import asyncio from contextlib import suppress from sanic import Blueprint, response from sanic.exceptions import abort from sanic_openapi import doc from .. import helpers, settings, utils from ..models import Template blueprint = Blueprint("Templates", url_prefix="/templates") @blueprint.get("/") @doc.summary("L...
import sqlite3 from modules.create_connect import create_or_connect as db_link from modules.utils import dict_factory from modules import vaccine_lot from contextlib import closing from datetime import datetime class Person: def __init__(self, person_id, first_name, last_name, address, phone, email, city, birth_...
# -*- coding: utf-8 -*- """ Exploring Box animation. Inquisitive pair of cubes of LEDs. """ import random from ..engine import Animation from ..sprites import Cube class SpiralPath: def __init__(self, margin, offset=0.0): steps_x = 8 - margin[0] steps_y = 8 - margin[1] self._max_z...
''' Base class for DataBear sensors ''' from databear.errors import SensorConfigError, MeasureError import datetime import time class Sensor: interface_version = '1.2' hardware_settings = {} measurements = [] #List of measurement names units = {} #List of units associated with measurement names mea...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Overrides the standard Polyencoder Agent to only return the attention weights. """ import torch import torch.nn impor...
""" 获取可用于训练网络的训练数据集 需要四十分钟左右,产生的训练数据大小3G左右 """ import os import sys sys.path.append(os.path.split(sys.path[0])[0]) import shutil from time import time import numpy as np from tqdm import tqdm import SimpleITK as sitk import scipy.ndimage as ndimage #Path to store processed data training_set_path = '/home/ubuntu/Rese...
# coding=utf-8 # 配置库 import torch from torch import nn from torch.autograd import Variable from torchvision import datasets # load model # 保存模型 # torch.save(model.state_dict(), './cnn.pth') # 定义卷积神经网络模型 class Cnn(nn.Module): def __init__(self, in_dim, n_class): # 28x28x1 super(Cnn, self).__init__() ...
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation from keras.layers import Bidirectional, GlobalMaxPool1D from keras.models import Model from keras import initializers, regularizers, constrain...
import optparse import os import sys import tempfile import src.model.network as network from src.model.mp2vec_s import MP2Vec __author__ = 'sheep' def HIN2vec(graph_fname, output_datafold, options): '''\ %prog [options] <graph_fname> <node_vec_fname> <path_vec_fname> graph_fname: the graph file ...
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import get_user_model from django import forms
from ltypes import i64 def fib(n: i64) -> i64: if n < 2: return n else: return fib(n - 1) + fib(n - 2) def main0(): ans: i64 ans = fib(15) assert ans == 610 def main(): # test of issue-529 ans: i64 ans = fib(10) assert ans == 55 main0() main()
''' @authors: Adrian Oeftiger @date: 17/04/2015 ''' import numpy as np from scipy.constants import c, epsilon_0, pi from scipy.interpolate import splrep, splev from functools import wraps from PyHEADTAIL.general.element import Element from PyHEADTAIL.general import pmath as pm from PyHEADTAIL.particles.slicing i...
from torch import nn import torch class GRU4REC(nn.Module): def __init__(self, input_size, hidden_size, output_size, num_layers=1, final_act='tanh', dropout_hidden=.5, dropout_input=0, batch_size=50, embedding_dim=-1, use_cuda=False): super(GRU4REC, self).__init__() self.input_size...
import enrich_db import couchDB import auth db = couchDB.Cloudant(auth.user, auth.password)
from aiger import atom from aiger_analysis import is_satisfiable x, y = atom('x'), atom('y') expr_sat = x | y expr_unsat = expr_sat & ~ expr_sat def test_satisfiable(): assert is_satisfiable(expr_sat) def test_satisfiable_2(): assert is_satisfiable(atom(True)) def test_unsatisfiable(): assert not is_...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of OTC Tool released under MIT license. # Copyright (C) 2016 T-systems Kurt Garloff, Zsolt Nagy from otcclient.core.OtcConfig import OtcConfig from otcclient.utils import utils_http from otcclient.utils import utils_http, utils_templates from otcclie...
# Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice import sys, os import random class areas: GOLD = ((900,600),(1000, 750)) # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection()...
from oadr_core.oadr_payloads.oadr_payloads_general import ELEMENTS, eiResponse def oadrCanceledOpt(code, description, requestID, optID): canceled_element = ELEMENTS['oadr'].oadrCanceledOpt( eiResponse(code, description, requestID), ELEMENTS['ei'].optID(optID) ) return canceled_element def...
# Problem: https://docs.google.com/document/d/1zaGh6rGnx07dI_ooeY8tp_y9h68fAMg6D3CA6a_giIY/edit?usp=sharing import math l,s=map(int,open(0)) print(math.ceil(l*20/s))