content
stringlengths
0
894k
type
stringclasses
2 values
from django.shortcuts import render # Create your views here. def about_view(request): return render(request, 'about/about.html')
python
# -*- coding: utf-8 -*- """ v13 model * Input: v12_im Author: Kohei <i@ho.lc> """ from logging import getLogger, Formatter, StreamHandler, INFO, FileHandler from pathlib import Path import subprocess import glob import math import sys import json import re import warnings import scipy import tqdm import click import...
python
from __future__ import absolute_import, unicode_literals import json from mopidy.models import immutable class ModelJSONEncoder(json.JSONEncoder): """ Automatically serialize Mopidy models to JSON. Usage:: >>> import json >>> json.dumps({'a_track': Track(name='name')}, cls=ModelJSONEn...
python
"""Generate a plot to visualize revision impact inequality based on data-flow interactions.""" import typing as tp import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib import axes, style from varats.data.databases.blame_interaction_database import ( BlameInteractionDatabase, ) fr...
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
python
from InsertionSort import insertionSort import math def bucketSort(customList): numBuckets = round(math.sqrt(len(customList))) maxValue = max(customList) arr = [] # Creating buckets for i in range(numBuckets): arr.append([]) # Shifting elemets to buckets for j in range(customList...
python
# -*- coding: utf-8 -*- import re import requests from datetime import datetime, timedelta from jobs import AbstractJob class Vaernesekspressen(AbstractJob): def __init__(self, conf): self.airport_id = 113 # Vaernes is the the only supported destionation self.from_stop = conf["from_stop"] ...
python
import jax.numpy as jnp from jax import vmap, grad, nn, tree_util, jit, ops, custom_vjp from functools import partial from jax.experimental import ode from collections import namedtuple GradientFlowState = namedtuple('GradientFlowState', ['B', 's', 'z']) def gradient_flow(loss_fn, init_params, inputs, labels, t_fi...
python
""" Crie um programa que aprove um emprestimo bancário, onde o programa leia: Valor da Casa / salário da pessoa / quantos anos será o pagamento Calcule o valor da prestação mensal, sabendo que ela não pode ser superior a 30% da renda da pessoa, se passar o emprestimo será negado """ import time valor_casa = float(inpu...
python
"""Core module for own metrics implementation""" from sklearn.metrics import mean_squared_error import numpy as np def rmse(y, y_pred): return np.sqrt(mean_squared_error(y, y_pred))
python
from django.contrib import admin from .models import Ballot, Candidate, SubElection, Election, Image, ElectionUser class CandidateAdmin(admin.StackedInline): model = Candidate extra = 0 class SubElectionAdmin(admin.ModelAdmin): model = SubElection inlines = [ CandidateAdmin, ] list_...
python
""" Defines the Note repository """ from models import Note class NoteRepository: """ The repository for the note model """ @staticmethod def get(user_first_name, user_last_name, movie): """ Query a note by last and first name of the user and the movie's title""" return Note.query.filter...
python
prefix = '14IDA:shutter_auto_enable2' description = 'Shutter 14IDC auto' target = 0.0
python
"""Pipeline subclass for all multiclass classification pipelines.""" from evalml.pipelines.classification_pipeline import ClassificationPipeline from evalml.problem_types import ProblemTypes class MulticlassClassificationPipeline(ClassificationPipeline): """Pipeline subclass for all multiclass classification pipe...
python
import os import sys import time import random import string import datetime import concurrent.futures # Import function from module from .program_supplementals import enter_key_only, exception_translator # Import function from 3rd party module from netmiko import ConnectHandler def file_output(ssh_res...
python
#------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. #-------------------------------------------------------------------------- import os i...
python
""" Module containing character class for use within world. """ from abc import ABC from .. import entity class Character(entity.Entity): """ Abstract class representing a character within a world. """ pass if __name__ == "__main__": pass
python
# Copyright 2017 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...
python
import unittest from pygments import lexers, token from gviewer.util import pygmentize, _join class TestUtil(unittest.TestCase): def test_pygmentize(self): python_content = """ import unittest class Pygmentize(object): pass""" result = pygmentize(python_content, lexer...
python
import json import unittest from contextlib import contextmanager @contextmanager def mock_stderr(): from cStringIO import StringIO import sys _stderr = sys.stderr sys.stderr = StringIO() try: yield sys.stderr finally: sys.stderr = _stderr cla...
python
''' Skip-thought vectors ''' from __future__ import print_function from __future__ import division from future import standard_library standard_library.install_aliases() from builtins import zip from builtins import range from past.utils import old_div import os import theano import theano.tensor as tensor import pic...
python
#!/bin/env python ## # @file This file is part of the ExaHyPE project. # @author ExaHyPE Group (exahype@lists.lrz.de) # # @section LICENSE # # Copyright (c) 2016 http://exahype.eu # All rights reserved. # # The project has received funding from the European Union's Horizon # 2020 research and innovation programme unde...
python
from sklearn.compose import ColumnTransformer from sklearn.decomposition import PCA from sklearn.impute import KNNImputer from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import RobustScaler class TrainModel(): @...
python
import cv2 from .drawBoxes import drawBoxes def addPedestriansToTrack(image, tracker, trackers, trackedObjectsNum): if trackers == None: trackers = cv2.MultiTracker_create() markedObjects = trackedObjectsNum while True: manualMarking = cv2.selectROI("Mark pedestrian to track", image) ...
python
import argparse import io import csv import scipy from scipy.sparse import csr_matrix import numpy as np import tensorflow as tf def add_data(r, indptr, indices, data, vocab): if len(r) > 1: label = r[0] for f in r[1:]: if f: k, v = f.split(':') idx = vocab.setdefault(k, len(vocab)) ...
python
import importlib import xarray as xr import numpy as np import pandas as pd import sys import os from CASutils import filter_utils as filt from CASutils import calendar_utils as cal importlib.reload(filt) importlib.reload(cal) def calcdeseas(da): datseas = da.groupby('time.dayofyear').mean('time', skipna=True) ...
python
# -*- coding: utf-8 -*- from __future__ import print_function import torch import spdnn torch.manual_seed(7) a = torch.rand(6, 6).cuda() a[a<0.6] = 0.0 at = a.t() print('at: ', at) b = torch.rand(6, 6).cuda() print('b: ', b) #c = spdnn.spmm(a, b) print('at shape: ', at.shape) torch.cuda.synchronize() c = spdnn.sparse...
python
# -*- coding: utf-8 -*- """ Created on 16 June 2021 Created by J Botha This script attempts to join the file provided city-hex-polygons-8.geojson to the service request dataset. When using the first 10 000 records from the service request dataset I seem to get no matches with Latitude and Longitude variable...
python
from collections import OrderedDict from Jumpscale import j JSBASE = j.baseclasses.object class ModelBase(j.baseclasses.object): def __init__(self, key="", new=False, collection=None): self._propnames = [] self.collection = collection self._key = "" self.dbobj = None sel...
python
# -*- coding: utf-8 -*- """ Created on Sep 6, 2020 @author: eljeffe Copyright 2020 Root the Box 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/licen...
python
# Copyright (C) 2021 Nippon Telegraph and Telephone Corporation # 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/LICE...
python
# 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. """This script demonstrates how the Python example service without needing to use the bazel build system. Usage: $ python example_compiler...
python
__all__ = ['Mode', 'Format'] from dataclasses import dataclass from enum import Enum from typing import Tuple class Mode(Enum): # Manually map these to the entries in .taco_compile.taco_type_header.taco_mode_t dense = (0, 'd') compressed = (1, 's') def __init__(self, c_int: int, character: 'str'): ...
python
from matplotlib import pyplot,gridspec,colors,patches import numpy import os from diatom import Calculate import warnings from scipy import constants h = constants.h cwd = os.path.dirname(os.path.abspath(__file__)) def make_segments(x, y): ''' segment x and y points Create list of line segments from x and y...
python
from __future__ import print_function import os, sys from chainer.links.caffe import CaffeFunction from chainer import serializers print('load VGG16 caffemodel') vgg = CaffeFunction('pretrained_model/VGG_ILSVRC_16_layers.caffemodel') print('save "vgg16.npz"') serializers.save_npz('pretrained_model/vgg16.npz', vgg)
python
from flask import Blueprint, request, jsonify, make_response from core import config import requests console = Blueprint('console', __name__) @console.route('/jobs', methods=['GET', 'POST', 'DELETE']) def jobs(): url = 'http://' + config['zmapd'] + '/api/jobs/' if request.method == 'GET': resp = req...
python
import hashlib from requests import post from observer_hub.util import logger PRIORITY_MAPPING = {"Critical": 1, "High": 1, "Medium": 2, "Low": 3, "Info": 4} class AdoClient(object): def __init__(self, organization, project, personal_access_token, team=None, issue_type="issue", rules="false",...
python
from terrascript import _resource class ignition_config(_resource): pass config = ignition_config class ignition_disk(_resource): pass disk = ignition_disk class ignition_raid(_resource): pass raid = ignition_raid class ignition_filesystem(_resource): pass filesystem = ignition_filesystem class ignition_file(_resou...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 20:39 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Nomina', '0004_auto_20170406_2015'), ] operations = [ migrations.RemoveField( ...
python
# -*- coding: utf-8 -*- from django.conf.urls import url from . import views urlpatterns = [ # Index Page url(r'^$', views.index, name='index'), url(r'^registBankAccount$', views.registBankAccount, name='RegistBankAccount'), url(r'^updateBankAccount$', views.updateBankAccount, name='UpdateBankAccount...
python
# -*- coding: utf-8 -*- # # Copyright (C) 2017 KuraLabs S.R.L # # 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...
python
import os import re import torch # Formatting strings (constant) save_format_str = "checkpoint{:08d}.pth" save_re_string = r"checkpoint(\d{8}).pth" assert re.match(save_re_string, save_format_str.format(0)) is not None def save_checkpoint(model_list, save_dir, epoch, optimizer=None, lr_scheduler=None): check...
python
# Purpose: Extract frames from video import cv2 import os import progressbar import threading class ExtractFrames: def __init__(self, video_path, person_name): self.video_path = video_path self.person_name = person_name if not os.path.isdir(f"Images/Known/{str(person_name)}"): ...
python
from pysnooper import snoop from tools import * import datetime import binascii import time import nfc #入退室の際のデータベース操作関数 def IO(ID: str, STATUS: str) -> None: conn=sql() cursor = conn.cursor() #入退室する前の人の数をチェック------------------------------------------------------ cursor.execute(f"select count(*) from ...
python
import yaml import os import time import re from my_devices import nxos1, nxos2 from netmiko import ConnectHandler from ciscoconfparse import CiscoConfParse from jinja2 import FileSystemLoader, StrictUndefined, Template from jinja2.environment import Environment env = Environment(undefined=StrictUndefined) #env.loade...
python
# -*- coding: utf-8 -*- import ipaddress from dnsdb_common.library.exception import BadParam from dnsdb_common.library.utils import format_ip from . import commit_on_success from . import db from .models import DnsColo from .models import DnsRecord from .models import IpPool from .models import Subnets class SubnetI...
python
# activity/urls.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.conf.urls import url from . import views_admin urlpatterns = [ # url(r'^$', views_admin.batches_home_view, name='batches_home',), # url(r'^batch_action_list/$', views_admin.batch_action_list_view, name='batch_action...
python
# -*- coding: utf-8 -*- """ .. module:: openzwave.network This file is part of **python-openzwave** project https://github.com/OpenZWave/python-openzwave. :platform: Unix, Windows, MacOS X :sinopsis: openzwave API .. moduleauthor: bibi21000 aka Sébastien GALLET <bibi21000@gmail.com> License : GPL(v3) **pyth...
python
# --- # name: web-csv # deployed: true # title: CSV Reader # description: Returns the data for the CSVs given by the URLs # params: # - name: url # type: array # description: Urls for which to get the info # required: true # examples: # - '"https://raw.githubusercontent.com/flexiodata/data/master/sample/sample-c...
python
# utilities for dealing with webtiles configuration. The actual configuration # data does *not* go in here. import collections import os.path import logging from webtiles import load_games server_config = {} source_file = None # light wrapper class that maps get/set/etc to getattr/setattr/etc # doesn't bother to im...
python
# black=\033[30m # red=\033[31m # green=\033[32m # orange=\033[33m # blue=\033[34m # purple=\033[35m # cyan=\033[36m # lightgrey=\033[37m # darkgrey=\033[90m # lightred=\033[91m # lightgreen=\033[92m # yellow=\033[93m # lightblue=\033[94m # pink=\033[95m # lightcyan=\033[96m # BOLD = \033[1m # FAINT = \033[2m # ITALIC ...
python
import json def save(name, csar): # TODO(@tadeboro): Temporary placeholder with open("{}.deploy".format(name), "w") as fd: json.dump(dict(name=csar), fd) def load(name): # TODO(@tadeboro): Temporary placeholder with open("{}.deploy".format(name)) as fd: return json.load(fd)["name"]
python
import os import bpy from bStream import * from itertools import chain import math def load_anim(pth): stream = bStream(path=pth) target_name = f"{os.path.basename(pth).split('.')[0]}_PTH" target_action = bpy.data.actions.new(f"{target_name}_PTH_ACN") target = bpy.data.objects.new(target_name, None) ...
python
# Generated by Django 3.2.5 on 2021-08-11 19:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Allergy', fields=[ ...
python
from src.extract_old_site.modules import excavation_details_page as exc_det import pathlib import os from unittest import mock import pytest # Structure 1, /dig/html/excavations/exc_is.html exc_is_html_str = """ <html><head><title>Excavating Occaneechi Town - [Excavations]</title></head> <frameset cols="408,*" border=...
python
import numpy as np import sys import os from keras.models import load_model sys.path.append("../utilities") import constants from data import get_train_test from metrics import plot_n_roc_sic datasets_c = ['h_qq_rot_charged', 'h_gg_rot_charged', 'cp_qq_rot_charged', 'qx_qg_rot_charged', 's8_gg_rot_charged', 'zp_qq_ro...
python
DEFAULT_REGID = u'strongswan.org' DEFAULT_ENTITY_NAME = u'strongSwan Project' DEFAULT_HASH_ALGORITHM = u'sha256'
python
import sys import os import cv2 # it is necessary to use cv2 library import numpy as np def main( background, input_filename, output_filename ): # Read the input image bak = cv2.imread(background) img = cv2.imread(input_filename) dif = img - bak dif = np.sqrt( np.sum( dif * dif, axis=2 ) ) ms...
python
from pycylon import Table from pycylon import CylonContext import numpy as np ctx: CylonContext = CylonContext(config=None, distributed=False) data_dictionary = {'col-1': [1, 2, 3, 4], 'col-2': [5, 6, 7, 8], 'col-3': [9, 10, 11, 12]} tb: Table = Table.from_pydict(ctx, data_dictionary) print("Convert to PyArrow Table"...
python
from django.forms import Form def set_form_widgets_attrs(form: Form, attrs: dict): """Applies a given HTML attributes to each field widget of a given form. Example: set_form_widgets_attrs(my_form, {'class': 'clickable'}) """ for _, field in form.fields.items(): attrs_ = dict(attrs) ...
python
# add_request_point.py from arcgis.features import Feature, FeatureSet from arcgis.geometry import Point from copy import deepcopy def add_request_point(gis, item_id, address_json, ip_address, user_agent, request_time): # get feature layer to edit layer_item = gis.content.get(item_id) feature_layer = layer...
python
from .utils import send_message __version__ = '1.0.1' __all__ = ['send_message']
python
# -*- coding: utf-8 -*- from django.dispatch import Signal validate_custom_order_field = Signal( providing_args=[ 'value', ] ) order_paid = Signal( providing_args=[ 'invoice', ] )
python
""" utility functions """ import pandas as pd import numpy as np TEST_DF = pd.DataFrame([1,2,3,4,5,6]) def five_mult(x): """multiplying a number by 5 function""" return 5 * x def tri_recursion(k): """recursion of a value""" if(k>0): result = k + tri_recursion(k-1) #...
python
# -*- coding: utf-8 -*- """ Created at 2019-10-30 @author: dongwan.kim Converting 'https://nlp.seas.harvard.edu/2018/04/03/attention.html' which is pytorch implementation to Keras implementation. # ToDo: copy layer test with simple multi hidden layer regression. """ import copy import numpy as np import math impor...
python
#!/usr/bin/env python import argparse import os parser = argparse.ArgumentParser(description='splits query name output by HAP.py and builds table required for ABCENTH') parser.add_argument('--table',default = None, help = 'table output by HAP.py') parser.add_argument('--hmm_dir',default = None, help = "director wi...
python
#!/usr/bin/env python3 """Three philosophers thinking and eating dumplings - deadlock happens""" import time from threading import Thread, Lock dumplings = 20 class Philosopher(Thread): def __init__(self, name: str, left_chopstick: Lock, right_chopstick: Lock) -> None: super().__init__() self.n...
python
#--------------------------------------------------------------------------- # Copyright 2013 The Open Source Electronic Health Record Agent # # 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 # ...
python
import tkinter from time import strftime top = tkinter.Tk() top.title('Clock') top.resizable(0, 0) def time(): string = strftime('%H:%M:%S %p') clockTime.config(text=string) clockTime.after(1000, time) clockTime = tkinter.Label(top, font=( 'courier new', 40,), background='black', foreground='white'...
python
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
python
# SPDX-FileCopyrightText: 2021 Gabriel Lisaca <gabriel.lisaca@gmail.com> # # SPDX-License-Identifier: Apache-2.0 import logging import pytest @pytest.fixture def placeholder_elvis_name(): return "placeholder" @pytest.fixture def placeholder_domain(): return "example.com" @pytest.fixture def placeholder_...
python
from exopy.tasks.api import (InstrumentTask) from atom.api import Float, Unicode, Str, set_default from qm.qua import * class ResumeProgramTask(InstrumentTask): """ Resumes a paused program. """ def __init__(self, **kwargs): super().__init__(**kwargs) def perform(self): self.driver.re...
python
#!/bin/python3 import math import os import random import re import sys # Complete the utopianTree function below. def utopianTree(n): value = 1 for i in range(n+1): if i%2 == 0 and i > 0: value += 1 if i%2 != 0 and i > 0: value *= 2 return value ...
python
import os, sys, imaplib, rfc822, re, StringIO import RPi.GPIO as GPIO import time server ='mail.xxx.us' username='juan@xxx.us' password='xxx' GPIO.setmode(GPIO.BOARD) GREEN_LED = 22 RED_LED = 7 GPIO.setup(GREEN_LED, GPIO.OUT) GPIO.setup(RED_LED, GPIO.OUT) M = imaplib.IMAP4_SSL(server) M.login(username, password)...
python
from engineauth import models from engineauth.middleware import AuthMiddleware import test_base import webapp2 from webob import Request __author__ = 'kyle.finley@gmail.com (Kyle Finley)' app = AuthMiddleware(webapp2.WSGIApplication()) class TestAppEngineOpenIDStrategy(test_base.BaseTestCase): def setUp(self):...
python
# -*- coding: utf-8 -*- import os import datetime import torch import torch.distributed as dist import torch.nn as nn import torch.multiprocessing as mp from parameters import get_args import pcode.create_dataset as create_dataset import pcode.create_optimizer as create_optimizer import pcode.create_metrics as creat...
python
import vigra from init_exp import meta from volumina_viewer import volumina_n_layer def view_train(): ds = meta.get_dataset('snemi3d_train') pmap = vigra.readHDF5('/home/constantin/Downloads/traininf-cst-inv.h5', 'data') volumina_n_layer([ds.inp(0), ds.inp(1), pmap, ds.seg(0),ds.gt()]) def view_test(res1...
python
#Test the frame by frame image output for image classification using a previous classifier from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient from azure.cognitiveservices.vision....
python
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.loss import _WeightedLoss, _Loss def one_hot(class_labels, num_classes=None): if num_classes==None: return torch.zeros(len(class_labels), class_labels.max()+1).scatter_(1, class_labels.unsqueeze(1), ...
python
from wordfilter import censored_words from lxml import etree import datetime import javmovie BASEURL="https://www.javlibrary.com/en/vl_searchbyid.php?keyword=" DIRECTURL="https://www.javlibrary.com/en/?v=" xpath_title = "/html/body/div[3]/div[2]/div[1]/h3/a" xpath_javcode = "/html/body/div[3]/div[2]/table/tr/td[2]/div...
python
#!/usr/bin/env python # Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P. # # 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...
python
import telebot import time import threading #Variables Globales enviados = 0 recibidos = 0 #Decoradores def controlador_mensajes(cant_enviar): """ controlador_mensajes: Cuenta cuantos mensajes recibe y envia, si recibe o envia mas de 20 entonces duerme por un segundo sacado de la documen...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import pytest import numpy as np from qtpy import QtWidgets, QtCore from planetaryimage import PDS3Image from ginga.qtw.ImageViewCanvasQt import ImageViewCanvas from pdsview import pdsview from pdsview.channels_dialog import ChannelsDialog from pdsview.histogram...
python
import copy import datetime import functools import inspect import os import textwrap import traceback from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Union import click import tqdm from experitur.core.context import get_current_context from experitur.core.parameters import ( Multi...
python
from importlib.util import find_spec from os.path import isfile, join import xdg.BaseDirectory from json_database import JsonStorage from xdg import BaseDirectory as XDG from ovos_utils.json_helper import load_commented_json, merge_dict from ovos_utils.log import LOG from ovos_utils.system import search_mycroft_core_...
python
''' TOOL SHARE steven small stvnsmll Full Project Structure: ~/toolshare |-- application.py # main script (this file) |__ /views # contains all blueprints for app.routes |-- __init__.py # empty |-- neighborhoods.py |-- tools_and_actions...
python
from collections import OrderedDict from .attributes import read_attribute_dict from .core import read_word, read_line # non-word characters that we allow in tag names, ids and classes DOM_OBJECT_EXTRA_CHARS = ('-',) def read_tag(stream): """ Reads an element tag, e.g. span, ng-repeat, cs:dropdown """ ...
python
import scipy.misc import scipy.io from ops import * from setting import * def img_net(inputs, bit, numclass): data = scipy.io.loadmat(MODEL_DIR) layers = ( 'conv1', 'relu1', 'norm1', 'pool1', 'conv2', 'relu2', 'norm2', 'pool2', 'conv3', 'relu3', 'conv4', 'relu4', 'conv5', 'relu5', 'pool5', 'fc6...
python
# -*- coding: utf-8 -*- # # Copyright (C) 2018 CERN. # # invenio-app-ils is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Search utilities.""" from invenio_search.api import RecordsSearch class DocumentSearch(RecordsSearch): "...
python
############################################################################# # # VFRAME # MIT License # Copyright (c) 2020 Adam Harvey and VFRAME # https://vframe.io # ############################################################################# import click @click.command('') @click.option('-i', '--input', 'opt_...
python
# 该模型模仿自 keras/examples/lstm_text_generation.py 和吴恩达老师课程中讲的并不相同 # 吴恩达老师的模型是训练一个RNN模型,然后每一次输入一个单词,预测出下一个最可能的单词作为输出 # 此模型则是利用 corpus 构建一个监督学习模型,模型的构成为,选择一个当前字母作为x,下一个字母作为y,从而构建模型 # 当前采用了每一个单词之后使用 \n 补齐,对模型效果可能会有点影响 from os import path from keras.models import Sequential from keras.layers import Dense, Dropout from keras...
python
import tensorflow as tf initializer = tf.keras.initializers.HeNormal() regularizer = tf.keras.regularizers.L1(l1=.001) inputs = tf.keras.Input(shape=(8,8,19)) filters = 32 x = tf.keras.layers.Conv2D(filters,(3,3),padding='same',kernel_regularizer=regularizer, bias_regularizer=regularizer, kernel_initializer=initializ...
python
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation setOutDir(__name__) import os,unittest from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle, LongTable from reportlab.platypus.doctemplate import PageAccumulator from reportlab.platypus.paragraph import P...
python
from qgis.PyQt.QtCore import Qt, QTimer from qgis.core import QgsProject, QgsRectangle, QgsWkbTypes from qgis.gui import QgsMapToolEmitPoint, QgsRubberBand POLLING_RATE_MS = 250 class WindowShow(QWidget): def __init__(self, mode='single_picture'): super().__init__() self.initUI() self....
python
from abc import ABCMeta, abstractmethod from collections import OrderedDict from modelscript.metamodels.classes.associations import opposite from modelscript.metamodels.objects import PackagableElement, Entity from modelscript.base.exceptions import ( UnexpectedCase, MethodToBeDefined) class Link(PackagableE...
python
# coding: utf-8 from atomate.vasp.config import ADD_WF_METADATA from atomate.vasp.powerups import ( add_wf_metadata, add_common_powerups, ) from atomate.vasp.workflows.base.core import get_wf __author__ = "Ryan Kingsbury, Shyam Dwaraknath, Anubhav Jain" __email__ = "rkingsbury@lbl.gov, shyamd@lbl.gov, ajain@...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import requests ID = 'id' NAME = 'nombre' PROV = 'provincia' PROV_ID = 'provincia_id' PROV_NAM = 'provincia_nombre' DEPT = 'departamento' DEPT_ID = 'departamento_id' DEPT_NAM = 'departamento_nombre' MUN = 'municipio' MUN_ID = 'municipio_id' MUN_NAM = 'municipi...
python
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import luigi from servicecatalog_puppet.workflow.tag_policies import tag_policies_base_task from servicecatalog_puppet.workflow.tag_policies import execute_tag_policies_task from servicecatalog_puppet.wor...
python
import os from os import path from imageio import imread from konlpy.tag import Hannanum from wordcloud import WordCloud, ImageColorGenerator """This code is to generate and to plot a wordcloud in Korean version. Of course it is possible to generate a simple wordcloud with the original codes. However due to the majo...
python
# -*- coding: utf-8 -*- """Aplicando estilo via classe. Adicionando uma classe através do método `add_class()` e arquivo css é caregado via linguagem de programação. """ import gi gi.require_version(namespace='Gtk', version='3.0') from gi.repository import Gtk, Gdk class MainWindow(Gtk.ApplicationWindow): def...
python