content
stringlengths
5
1.05M
import numpy as np import torch.nn as nn import torch from .shared import Conv_Block from collections import OrderedDict class Conv_net(nn.Module): def __init__(self, input_dim, num_conv_layers, num_conv_layers_mem, hidden_dim, kernel_size, dilation_rate): """ Initialize ConvLSTM cell. Par...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 04/01/2020 """ import gym import numpy from gym.spaces import Discrete __all__ = ["NormalisedActions"] class NormalisedActions(gym.ActionWrapper): def reverse_action(self, a: ...
print(__file__) import psutil import nslsii # warn the user if there is another bsui running def get_bsui_processes(): bsui_processes = [] for process in psutil.process_iter(): if "bsui" in process.name(): bsui_processes.append(process) return bsui_processes bsui_processes = get_bsui...
ticker = { 'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1 } aunts = {} for line in open('input.txt').readlines(): l = line.split() x = {} for i in range(2, 8, 2): x[l[i].replace(':', '')] = int(l[i + 1].replac...
#!/usr/bin/env python3 # Read a symbol file and a source file. # Replace symbol addresses with names in the source file. # XXX does not handle addresses split into parts, like: # lui $a0, xxxx # ori $a0, xxxx import sys def readSyms(path): syms = {} with open(path) as file: while True: line...
# # Autogenerated by Thrift Compiler (0.11.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py:new_style,no_utf8strings # from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException from thrift.protocol.TProtocol import TProtocolException fr...
# to use this install package #ModuleNotFoundError: No module named 'github' # pip install PyGithub from github import Github import requests # remove the minus sign from the key # you can add this to your code just don't commit it # or use an API key to your own repo g = Github("57327b6f6a7fc5603ac601050b6f1a0b1ff6b1...
class Quiz: def __init__(self,question, alt1, alt2, alt3, alt4, correct): self.question = question self.alt1 = alt1 self.alt2 = alt2 self.alt3 = alt3 self.alt4 = alt4 self.correct = correct def check_anser(self, anser): self.anser = anser score =...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2020, Brian Scholer (@briantist) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: vault_test_auth author: ...
from google.oauth2 import id_token from google.auth.transport import requests from datetime import datetime CLIENT_ID_1 = '242715444435-ss081r800k4ib43o4cusd3au76bktfb3.apps.googleusercontent.com' CLIENT_ID_2 = '593881631501-9ah6is5851aass4lonh1lptc69slfo0e.apps.googleusercontent.com' def has_authorization(token): ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 19 14:03:15 2018 @author: Sudhanva """ from tkinter import * root = Tk() frame = Frame(root) frame.pack() bottomframe = Frame(root) bottomframe.pack(side = BOTTOM) redbutton = Button(frame, text = 'Red', fg = 'red') redbutton.pack(side = LEFT) greenbutton = Button(fra...
# # Copyright Michael Groys, 2012-2014 # import miner_globals from base import * def p_for_command(p): '''command : for_command''' p[0] = p[1] def p_for_select_command(p): '''for_command : FOR SELECT aggregated_named_expression_list''' p[0] = ForSelectCommand(p[3]) def p_for_dinstinct_select_command...
import multiprocessing as mp import tqdm import numpy as np import json import sys import pycocotools.mask as maskUtils def read_annot(ann, h, w): segm = ann['inmodal_seg'] if isinstance(segm, list): modal = maskUtils.decode(maskUtils.frPyObjects(segm, h, w)) else: modal = maskUtils.decode(...
# coding=UTF-8 import os import json import importlib from getgauge.python import before_spec, data_store, step, Messages from testlib.infrustructure.match.Match import Match from testlib.infrustructure.devices.Device import Device @before_spec def before_spec_hook(context): specificationPath = os.path.dirname(c...
def application(env, start_response): start_response('200', [('Content-Length', '1')]) exit() return [b'X']
# ---------------------------- # Class to implement the SIA DC03 message # (c 2018 van Ovost Automatisering b.v. # Author : Jacq. van Ovost # ---------------------------- import time from dc09_spt.param import * import logging """ Copyright (c) 2018 van Ovost Automatisering b.v. Licensed under the Apache Lic...
from __future__ import unicode_literals import frappe from frappe.utils import getdate, validate_email_add, today import datetime from planning.planning.myfunction import mail_format_pms,actual_date_update,close_task_update @frappe.whitelist() def report_in_out(doctype=None,date1=None,date2=None): filter = "" ...
# coding=utf-8 """Function generators .. moduleauthor:: Dieter Moser <d.moser@fz-juelich.de> """
from xbos import get_client from xbos.services.mdal import * from xbos.services.hod import HodClient import pandas as pd import pytz from sklearn.metrics import mean_squared_error from dateutil import rrule from datetime import datetime, timedelta # data clients mdal = MDALClient("xbos/mdal") hod = HodClient("xbos/hod...
# Generated by Django 3.0.6 on 2021-08-03 10:49 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0015_auto_20210...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ CaesarCypher.py This module implements simple writing and reading methods for files based on the Caesar cypher. It's a quite simple encryption method: every character is converted to its numerical value, a value is added to it and then it is reconverted to a characte...
import csv import statistics class VrmPrinter: def __init__(self): self.voltage = None self.fluorescence = list() self.voltages = list() self.fluorescences = list() def add(self, voltage: float, fluorescence: float): if self.voltage is not None and self.voltage != vol...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import os import csv import getopt import sys import argparse def get_case_info(file_writer, file_content, reason, status="Pass"): out = [] tmp_out = [] info = [] ge_out = [] hgvs_out = [] final_syn = [] all_gene = [] all_omim...
class Group(object): def __init__(self): self.children = [] def add(self, child): self.children.append(child) return child def update(self, time): self.children[:] = [ child for child in self.children if child.exists()] for child in self.children: ...
#!/usr/bin/env python import Adafruit_ADS1x15 import time import rospy import numpy from std_msgs.msg import String,Int32MultiArray from rospy.numpy_msg import numpy_msg from rospy_tutorials.msg import Floats def talker(): pub = rospy.Publisher('line_follower_topic', numpy_msg(Floats),queue_size=10) rospy.ini...
from CGATReport.Tracker import * from cpgReport import * from CGATReport.odict import OrderedDict as odict ########################################################################## class cgiAnnotations(cpgTracker): """Breakdown of overlap of predicted CGIs with genomic regions """ mPattern = "cgi_annotat...
import numpy as np from PIL import Image from matplotlib import pyplot as plt def load_image(file_path): img = Image.open(file_path) img_data = np.array(img) return img_data def visualize(img_data): print(img_data.shape) plt.axis("off") plt.imshow(img_data) plt.show() def visualize_dua...
import pandas as pd import requests import io import os import json import plotly.express as px import plotly.figure_factory as ff import numpy as np import pathlib import statsmodels.api as sm import numpy as np import matplotlib.pyplot as plt pd.options.plotting.backend = "plotly" def fetch_json_map(): if not os.p...
import os import re import logging from virttest import data_dir from virttest import utils_misc from avocado.utils import process from avocado.core import exceptions from autotest.client.shared import error @error.context_aware def run(test, params, env): """ 'thin-provisioning' functions test using sg...
#!/usr/bin/env python """Process that loads the datastore""" __author__ = 'Michael Meisinger, Thomas Lennan' """ Possible Features - load objects into different datastores - load from a directory of YML files in ion-definitions - load from a ZIP of YMLs - load an additional directory (not under GIT control) - change...
""" Used to track events in tests. """ # Enthought library imports. from traits.api import HasTraits, List, Str, Tuple class EventTracker(HasTraits): """ Used to track traits events. """ # The traits events that have fired. # # This is a list of tuples in the form:- # # (obj, trait_name, ol...
#!/usr/bin/env python ''' This script extracts info coded with intervals for any data with CHROM POS coordinates. scores.file: CHROM startPOS endPOS 12.4.SNPs.haplotype scaffold_1 679 733 0.0 scaffold_1 1733 7988 0.0 scaffold_1 8339 10393 0.0 scaffold_1 10827 11638 0.0 scaffold_1 12147 14440 0.0 scaffold_1 14986 4114...
#! /usr/bin/env python # Copyright (c) 2016-2018, Rethink Robotics 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 ...
#!/usr/bin/env python3 # -*- encoding: utf8 -*- """ TBD """ import argparse import itertools import os import re import sys parser = argparse.ArgumentParser() parser.add_argument( "--out", "-o", type=str, help="Path to output directory.", ) parser.add_argument("--data", "-d", type=str, help="Path ...
class BNode: def __init__(self, val=None, left=None, right=None): self.val = val self.left = left self.right = right def _unival(root): if root == None: return (False, 0) if root.left == None and root.right == None: return (True, 1) l_count, r_count = 0, 0 ...
from python_experimenter.database_handler import ( create_database_handler_from_config, MySqlDatabaseHandler, ) class TestDatabaseHandlerCreation: def test_database_handler_creation(self): p = { "keyfields": ["x", "y"], "resultfields": ["addition", "multiplication"], ...
#!/usr/bin/env python3.6 from Locker import Urufunguzo from Credentials import Credential import pyperclip #Functions for Creating User def hanga_user(name,fone,names,mail,ibanga): ''' Function to create a new user ''' user = Urufunguzo(name,fone,names,mail,ibanga) return user def save_users(Locker...
import numpy as np import pylab as plt from matplotlib.patches import Ellipse fig=plt.figure(figsize=(22.62372, 12)) ax = fig.add_subplot(111) fig.subplots_adjust(bottom=.2) font1={'family':'Arial', 'color' : 'b', 'weight' : 'normal', 'size' : 30, } font2={'family':...
from dataset.dataset import * from torch.utils.data import Dataset, DataLoader import getpass import os import socket import numpy as np from dataset.preprocess_data import * import torch from models.model import generate_model from opts import parse_opts from torch.autograd import Variable import torch.nn.functional a...
class MyHashMap: class Entry: def __init__(self, key, val, next): self.key = key self.val = val self.next = next def __init__(self): self.mod = 100003 self.list = [self.Entry(-1, -1, None) for _ in range(self.mod)] def _index(self, key): ...
# 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, ...
#!/usr/bin/python # Codeing By IOXhop : www.ioxhop.com # Sonthaya Nongnuch : www.fb.me/maxthai import time import IOXhop_MCUio as mcu def main(): mcu.begin(0x08) mcu.mode(9, mcu.OUTPUT) while True: mcu.tone(9, 2000) # Send sound 2KHz to pin 2 time.sleep(1) mcu.Dtone(9) # Cancel send sound to pin 2 time...
import sys # taken from https://stackoverflow.com/a/11325249 class Logger(object): def __init__(self, *files): self.files = files def write(self, obj): for f in self.files: f.write(obj) f.flush() def flush(self): for f in self.files: f.flush() ...
# Copyright 2016, Kevin Christen and the juno-addresses contributors. from collections import defaultdict import argparse import csv import sys from juno_addresses import parser COLUMNS = [ 'Name', 'Given Name', 'Family Name', 'Nickname', 'E-mail 1 - Value', 'Phone 1 - Type', 'Phone 1 - ...
import numpy as np from .Scan import Scan from .Annotation import Annotation import matplotlib.pyplot as plt from skimage.measure import find_contours from matplotlib.widgets import Slider def consensus(anns, clevel=0.5, pad=None, ret_masks=True): """Return the boolean-valued consensus volume amongst the provi...
''' AAA lllllll lllllll iiii A:::A l:::::l l:::::l i::::i A:::::A l:::::l l:::::l iiii A:::::::A l:::::l l:::::l ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import functools def ignore_exception_decorator(func): """どんなエラーも無視してしまうデコレータ""" @functools.wraps(func) def ignore_exception(*args, **kargs): try: return func(*args, **kargs) except: pass return ignore_exception
import base64 from datetime import datetime import logging import re import json from sets import Set from datawinners.project.views.data_sharing import DataSharing from datawinners.alldata.helper import get_all_project_for_user from datawinners.blue.correlated_xlxform import ParentXform from django.http import HttpRe...
colormode(RGB) fill(0) rect(0,0,100,100) fill(0,0,0) rect(100.0,0,100,100) colormode(CMYK) fill(0,0,0,1) rect(200.0,0,100,100)
import turtle def draw_green_triangle(ram): ram.color("#64DD17") ram.begin_fill() for i in range(1,3): ram.forward(100) ram.left(120) ram.forward(100) ram.end_fill() def draw_white_triangle(guru): guru.left(120) guru.forward(100) guru.left(120) ...
def bit_req(A,B): """ Bits required to convert int A to int B """ c=A^B return countOnes(c) def countOnes(c): count=0 if c == 1: return 1 while(c>=1): b=c%2 if b == 1: count+=1 c=c//2 return count print bit_req(4,7)
""" Simulates the actual hardware. This is the package used by the unit tests. """ import time import config heating = False cooling = False stirring = False temperature = -1 timer = time.time(); def log(message): print('harware.simulation - ' + str(message)) def secondSinceStart(): """ The number of ...
import connexion from flask_cors import CORS if __name__ == '__main__': capp = connexion.FlaskApp(__name__, specification_dir='specs/') capp.add_api('blog.yaml', arguments={'title': 'Hello World Example'}) CORS(capp.app) capp.run(host='0.0.0.0', debug=True, port=9090)
#python import ast import jwt #web app import tornado from tornado.ioloop import IOLoop import jinja2 from flask import Flask, redirect, url_for, session, request, jsonify, render_template #pdf context import fitz #internal from handlers.apiBaseHandler import BaseHandler from models import User, Document, Link, signR...
import websockets, json, traceback, os, asyncio, inspect, logging import websockets.client import websockets.server from websockets.exceptions import ConnectionClosedOK, ConnectionClosedError from .client_management.client import Client from .inventory_management.skin_manager import Skin_Manager from .randomizers.ski...
# -*- coding: utf-8 -*- """ GroundwaterDupuitPercolator Component @author: G Tucker """ import numpy as np from landlab import Component from landlab.utils import return_array_at_node, return_array_at_link from landlab.grid.mappers import map_mean_of_link_nodes_to_link ACTIVE_LINK = 0 class GroundwaterDupuitPerco...
# Copyright (C) 2019-2020, TomTom (http://tomtom.com). # # 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 o...
import logging from django import forms from django.forms import ModelForm from django.template.defaultfilters import slugify from crispy_forms.bootstrap import FieldWithButtons, StrictButton from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, Div, Field, Layout, Submit from .models impo...
from src.binary_lane_filter import apply_road_lane_binary_filter import numpy as np import cv2 from src.warp import ImageWarp from src.line import TrafficLine from src.visualisation import window_corners, color_window_pixels from src.curvature import estimate_lane_curve_radius_m from src.camera_callibration import Cam...
import unittest from src.morphothec import Morphothec from src.generator import word_for_keys import src.composer as composer class FormTests(unittest.TestCase): def setUp(self): self.morphothec = Morphothec(["data/morphs-latin.json", "data/morphs-greek.json"]) # Tests that prefix sound assimilation ...
import json from unittest.mock import Mock import graphene import pytest from django.shortcuts import reverse from tests.utils import get_graphql_content from saleor.product.models import ( Category, ProductAttribute, AttributeChoiceValue) from saleor.graphql.product.utils import attributes_to_hstore from saleor.g...
class A1: foo = <error descr="Unresolved reference 'B1'">B1</error>() class B1: pass class A21: class A22: bar = <error descr="Unresolved reference 'B2'">B2</error>() class B2: pass class A31: def baz(self): class A32: egg = B3() class B3: pass
import numpy as np import matplotlib.pyplot as plt """ Extensions of DictLearner that keep track of how well they have recovered a known sparse model. The data passed in should be a StimSet.ToySparseSet object. """ def make_fit_learner_class(Learner): """Given a particular DictLearner class, returns a...
from flask import jsonify from lin import route_meta, group_required, login_required from lin.exception import Success from lin.redprint import Redprint from app.validators.forms import ThirdClientForm,WxClientForm from app.models.third_client.third_bind import ThirdBind member_api = Redprint('member') @member_api.r...
""" Copyright (c) 2013, rhambach. This file is part of the TEMareels package and released under the MIT-Licence. See LICENCE file for details. """ import Release __all__ = ["aperture","ecal","qcal","gui","tools"] __version__ = str(Release.version); __author__ = ", ".join(Release.authors); __license__ = str(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : scriptsytSequence.py # Author : yang <mightyang@hotmail.com> # Date : 10.03.2019 # Last Modified Date: 14.03.2019 # Last Modified By : yang <mightyang@hotmail.com> # from ytLoggingSettings import yl import re import os impo...
from axelrod.action import Action from axelrod.player import Player C, D = Action.C, Action.D class VeryBad(Player): """ It cooperates in the first three rounds, and uses probability (it implements a memory, which stores the opponent’s moves) to decide for cooperating or defecting. Due to a lack ...
# coding: utf-8 # flake8: noqa """ Home Connect API This API provides access to home appliances enabled by Home Connect (https://home-connect.com). Through the API programs can be started and stopped, or home appliances configured and monitored. For instance, you can start a cotton program on a washer and ge...
# -*- coding: utf8 -*- # ============LICENSE_START==================================================== # org.onap.vvp/validation-scripts # =================================================================== # Copyright © 2019 AT&T Intellectual Property. All rights reserved. # ===========================================...
from dataclasses import dataclass from pandas import Series """ This file demonstrates the usage of a dataclass to abstract away data operations. Using dataclasses can be useful for working with data where conversion from Dataframes or JSON is required. """ @dataclass class OtherSampleDataItem: state: str ...
from tabulate import tabulate from collections import OrderedDict #we create a jobContext Class class JobContext(object): def __init__(self,sc): self.counters = OrderedDict() self.constants = OrderedDict() self._init_accumulators(sc) # accumulators are here! self._init_shared_data...
AUTOLBOX_HEURISTIC_LINE = True AUTOLBOX_HEURISTIC_HIST = True AUTOLBOX_HEURISTIC_STACK = True
from django.contrib.admin import register, ModelAdmin from django_admin_inline_paginator.admin import TabularInlinePaginated from .models import Country, State class StateAdminInline(TabularInlinePaginated): fields = ('name', 'active') per_page = 1 model = State @register(State) class StateAdmin(ModelA...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
import argparse import base64 import binascii import copy import hashlib import inspect import io import os import shlex import struct import sys import time import zlib import string __version__ = "0.1 dev" PYTHON2 = sys.version_info[0] < 3 # True if on pre-Python 3 def add_crc(args): f...
import stylecloud ip_files = ('top_authors_2019.csv', 'top_authors_2021.csv') op_files = ('top_authors_2019.png', 'top_authors_2021.png') for ip_file, op_file in zip(ip_files, op_files): stylecloud.gen_stylecloud(file_path=ip_file, icon_name='fas fa-book-open', ...
class KitsuError(Exception): pass
class Load: def __init__(self) -> None: self def __str__(self) -> str: return str(self.__dict__)
PACKAGE_NAME = "pyreess" __version__ = "1.0" DESCRIPTION = "CLI application for deterministic password generation and recall"
from vampire.modules.encoder import * from vampire.modules.pretrained_vae import PretrainedVAE from vampire.modules.token_embedders.vampire_token_embedder import VampireTokenEmbedder from vampire.modules.vae import LogisticNormal from vampire.modules.vae import VAE
from paraview.simple import * import paraview.benchmark as pvb pvb.logbase.maximize_logs() w = Wavelet() w.UpdatePipeline() pvb.logbase.get_logs() pvb.logbase.print_logs() pvb.logbase.dump_logs("benchmark.log") pvb.logbase.import_logs("benchmark.log") print('='*40) print('Raw logs:') print('='*40) pvb.logbase.print...
#!/usr/bin/env python # encoding: utf-8 from collections import namedtuple def _create_named_tuple(name, values): '''Helper function for creating a named tuple with the first letter of each of the values as the names of its fields. :param name: the name of the class that is generated :param values: t...
import configparser config = configparser.ConfigParser() config.sections() config.read('example.cfg') config.sections() for key in config['SectionOne']: print(key) config['SectionOne']["status"]
# This sample tests the "pseudo-generic class" functionality, # where a class is made into a generic class in cases where # it has no annotated constructor parameters. # We use "strict" here because we want to ensure that there are # no "unknown" types remaining in this file. # pyright: strict class Foo: def __in...
# coding: utf-8 import socketserver import sys import os # Copyright 2013 Abram Hindle, Eddie Antonio Santos # # 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/li...
#!/usr/bin/python # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'support...
from PIL import Image from PIL import Image import pandas as pd import numpy as np import torch.utils.data from collections import OrderedDict import torch def rgb_loader(path): return Image.open(path).convert('RGB') class VideoDataset(torch.utils.data.Dataset): def __init__(self, datalist_config, transfor...
# 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 # d...
import os, sys import argparse import numpy as np def convert_to_conll(npz_file, bpe_file, conll_file): output=np.load(npz_file) labels=output['labels'] deps =output['deps'] f_conll=open(conll_file, 'w') idx=0 for idx, bpe in enumerate( open(bpe_file, 'r') ): #print(idx, bpe.strip()) words...
redirect_domain = 'brewgrindwater.com'
from courier.models import UserSendTime from fuauth.models import User from functional_tests.utils import SeleniumTestCase class TestAdmin(SeleniumTestCase): """ Tests for the FiveUp admin dashboard. """ def setUp(self): self.admin_user = User.objects.create_superuser( name="Noof...
from typing import Sequence from ..base import BaseAPIClass from ..libraries import Color from .vector import Vector from ..utils import to_dict, to_dict_seq class Polygon(BaseAPIClass): """Represents the berkerdemoglu.engine.graphics.math.geometry.Polygon3D class.""" def __init__(self, color: Color, *vertices: S...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumOfLeftLeaves(self, root): """ Using DFS O(2^N) :type root: TreeNode :rtype: int ...
import chainer from chainer.functions.array import broadcast from chainer.functions.array import reshape def scale(x, y, axis=1): """Elementwise product with broadcasting. Computes a elementwise product of two input variables, with the shape of the latter variable broadcasted to match the shape of the fo...
#!/usr/bin/python # The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This example shows how to use dlib's face recognition tool. This tool maps # an image of a human face to a 128 dimensional vector space where images of # the same person are near to each other and ima...
#!/usr/bin/env python from assignment8 import StressStrainConverter import numpy as np import scipy.integrate from PyTrilinos import Epetra # + class EpetraParallelToughness(StressStrainConverter): def __init__(self, filename, comm): super().__init__(filename) self.comm = comm self.rank ...
from pandas_profiling.report.presentation.core.overview import Overview from pandas_profiling.report.presentation.flavours.html import templates class HTMLOverview(Overview): def render(self): return templates.template("info.html").render(**self.content)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, unicode_literals import argparse import sys import torch from onmt.utils.misc import get_logger from onmt.translate.translator import build_translator from tqdm import tqdm from modifications.util import file_cached_function import js...
"""labpals package initializer.""" import flask app = flask.Flask(__name__) # pylint: disable=invalid-name app.config.from_object("labpals.config") app.config.from_envvar("LABPALS_SETTINGS", silent=True) import labpals.model # noqa: E402 pylint: disable=wrong-import-position import labpals.utils # noqa: E402 pyl...
from django.http import FileResponse # Create your views here. def send_image(request, name="icon.jpg"): img = open(f"./templates/{name}", 'rb') response = FileResponse(img) return response