text
stringlengths
38
1.54M
import numpy as np from numpy import linalg as LA import pandas as pd # mean def mean(x): return np.round(x.mean(axis=0),3) # std def std(x): return np.round(x.std(axis=0),3) # covarian-matrix def cov_matrix(x): fact = x.shape[0] - 1 return np.round(np.dot((x-mean(x)).T,(x-std(x)))*(1/fact),3) # multivaria...
def main(): a = 1 b = a * a return b def hello(): return 'hello123' def add(a, b): return a + b def process(kw): return str(kw['name']) + str(kw['value']) # if __name__ == '__main__': # kw = {'name': 'liuyang', 'value': 123} # print(process(**kw))
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
# -*- coding: utf-8 -*- """ Created on 2020/5/4 7:59 @author: dct """ import requests from lxml import etree import re header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36', 'Referer': 'https://movie.douban.com/top250?st...
import dash import dash_core_components as dcc import dash_html_components as html import pandas import plotly.express as px app = dash.Dash(__name__) data_frame = pandas.DataFrame({ "Day": ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"], "Value": [9.5, 8.7...
import numpy as np from easydict import EasyDict para = EasyDict() # 6: cos, sin, x, y, w, l # 5: r, x, y, w, l para.box_code_len = 6 if para.box_code_len == 6: para.target_mean = np.array([0.799, -0.053, 0.194, 0.192, 0.487, 1.37], dtype=np.float32) para.target_std_dev = np.array([0.325, 0.504, 0.537, 0....
from PyQt4 import QtGui from PyQt4 import QtCore from AlignmentTableAbstractModel import TableAbstractModel as alignment_model from InputDialogWidget import InputDialog as input_dialog import random import sys class AlignmentWindow(QtGui.QMainWindow): def __init__(self, sequences): super(AlignmentWindo...
# -*-coding:utf-8-*- import codecs import csv import os import pandas as pd import util.common_util as my_util from collections import Counter # 证据名称列表 evidence_list = list() # 笔录正文字典 文件名:内容 content_dict = dict() # 笔录中举证质证文本 文件名:内容 train_evidence_paragraph_dict = dict() dev_evidence_paragraph_dict = dict() test_evid...
from get_ohlcv_data import load_asset_dfs from strategies.n_over_a_strat import NOverAStrategy TEST_START_DATE = '2019-01-01' TEST_END_DATE = '2021-01-01' INITIAL_CASH=10000 COMMISSION_AND_SLIPPAGE = 0.01 def test_backtest_strategy(): asset_dfs = load_asset_dfs() strategy = NOverAStrategy(asset_dfs) strategy.b...
import json from talentmap_api.common.serializers import PrefetchedSerializer, StaticRepresentationField from talentmap_api.messaging.models import Notification class NotificationSerializer(PrefetchedSerializer): owner = StaticRepresentationField(read_only=True) class Meta: model = Notification ...
import json import os def config() -> dict: file = os.path.join(os.path.dirname(__file__), 'config.json') with open(file) as fh: return json.load(fh)
import io import json from waitress import serve from flask import Flask, request, render_template, make_response from utils import extension_validation, process_data_for_output app = Flask(__name__) @app.route('/', methods=["POST", "GET"]) def form(): if request.method == 'POST': f = request.files['da...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig import os from django.conf import settings class LineServerConfig(AppConfig): name = 'line_server' def ready(self): pre_process() # one-time initialization when server is up def pre_process(): fro...
class Solution: def decodeString(self, s): curstring, curnum = "", 0 stack = [] for c in s: if c == '[': stack.append(curnum) stack.append(curstring) curstring = '' curnum = 0 elif c == ']': ...
# -*- coding: utf-8 -*- import os path = r'C:\Users\sssh\OneDrive\Desktop\Новая папка' def rename_all_files(path): for root, dirs, files in os.walk(path): for _file in files: if _file.endswith('.txt'): file_name = _file.split('.') remove_part = file_name[0][:len...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # 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 # ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-14 10:05 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations...
# Generated by Django 2.0.3 on 2019-11-13 09:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0007_auto_20191113_1155'), ] operations = [ migrations.RemoveField( model_name='article', name='img', ...
def fac(x): if x == 1: return 1 else: return x*fac(x-1) def fib(n): if n < 2: return 1 else: return fib(n - 1) + fib(n - 2) fib_monster = fib(10) def bar(x): return 5
# -*- coding: utf-8 -*- # # Copyright 2016-2023 BigML # # 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 ...
from Eulerstep import * import numpy as np #simulates the sin/cos function def func(t, vector): y_out = np.zeros((2, 1)) x = -vector[1] y = vector[0] y_out[0][0] = x y_out[1][0] = y return y_out.T[0] # vector_euler(lorenz, 0, 1, [1, 1, 1], 0.05, "plot") # vector_euler(lorenz, 0, 1, [1, 1, ...
species( label = 'CC(C[CH]CC[O])OO(3840)', structure = SMILES('CC(C[CH]CC[O])OO'), E0 = (-32.494,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2750,2770,2790,2810,2830,2850,1425,1437.5,1450,1225,1250,1275,1270,1305,1340,700,750,800,300,350,400,2750,2800,2850,1350,15...
"""Python Cookbook Chapter 14, recipe 6, Controlling complex sequences of steps. """ import argparse import subprocess from unittest.mock import Mock, call from pytest import * # type: ignore import Chapter_14.ch14_r06 @fixture # type: ignore def mock_subprocess_run(): return Mock( return_value=Mock( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SearchAbilityOrderInfoOpenApi(object): def __init__(self): self._access_type = None self._app_name = None self._app_status = None self._audit_status = None ...
# Generated by Django 2.0.7 on 2018-11-26 23:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flujo', '0001_initial'), ] operations = [ migrations.AlterField( model_name='obligaciones', name='tasa_obligacion', ...
import sys from collections import defaultdict import numpy from sklearn.cross_validation import StratifiedKFold from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import Normalizer from sklearn.svm import LinearSVC from sklearn.dummy import DummyClassifier from sklearn.metrics imp...
# Exceptions are used to handle the errors in the python program # In a program exit code = 1, means program "Crashed" # code = 0 means "Success" # An exception is a kind of error that crashes our program # We use try, except block to handle exceptions that are raised in the programs try: age = int(input("Age: ")...
import logging import os import shutil import pytest from rasa import data, model from rasa.cli.utils import create_output_path from rasa.nlu import data_router, config from rasa.nlu.components import ComponentBuilder from rasa.nlu.model import Trainer from rasa.nlu import training_data from rasa.nlu.config import Ra...
from .base import * SECRET_KEY = '9875wetwrewyyu69854769kjhsdfiuy*^b32kw(993!sx1' SELENIUM_TESTS_ENABLED = True SELENIUM_DRIVER = 'Firefox'
import datetime import sys from dataHandler import getSeasonFilePath from colorama import Fore from leagues import selectLeague, getSeasonOptions from teamsetCmd import executeTeamSet from reindexCmd import executeReIndex from battlerecordCmd import registerBattleRecord TITLE = "Pokemon Go PvP Data Collector" VERSIO...
# -*- coding: utf-8 -*- # scraper.py for 17-QC-HealthAndSocialServices import urllib.request import re import os import csv import sys import ipgetter import ipcalc from urllib.error import URLError, HTTPError, ContentTooShortError from urllib import robotparser from lxml.html import fromstring, tostring from lxml imp...
# Generated by Django 2.2.5 on 2021-06-15 18:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('review', '0001_initial'), ] operations = [ migrations.DeleteModel( name='reviewOfFilm', ), ]
from c_s_app.models import * import csv import os def data_to_db(): file_name = '10full_columns.csv' pwd = os.path.dirname(__file__) file_path = pwd + '/' + file_name list_f = [] with open(file_path, 'r', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader:...
''' 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 use this ...
# n^e module p def tinh_luy_thua(n,e,p): result = 1 while e != 0: if(e%2 == 1): result = result*n%p e = (e - 1) n = n*n%p e = e//2 return result #phep chia da thuc trong GF(2) # c(x) = a(x)*b(x) mod q(x) # a(x) = a[1]x + a[0] and b(x) = b[1]x + b[0] # q(x) =...
"""Tests for Action Classification with OTX CLI.""" # Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import json import os from pathlib import Path from timeit import default_timer as timer import pytest from otx.cli.registry import Registry from tests.regression.regression_test_helpers ...
# Generated by Django 3.0.5 on 2020-09-07 09:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('doctors', '0012_remove_symptom_age'), ] operations = [ migrations.AddField( model_name='symptom', name='age', ...
# Here, we are calculating the excess coalescent laod that is bround by the difference in models. from spectra import * from pathlib import Path from tqdm import tqdm if __name__ == "__main__": tmp_store = Path("data") n_range = [50, 100, 200] N = 1000 mu = 1e-8 ns_range = [0, 1, 5, 10, 20, 50] ...
from easydict import EasyDict as edict # init __C_JHU = edict() cfg_data = __C_JHU __C_JHU.TRAIN_SIZE = (512, 1024) __C_JHU.DATA_PATH = '../ProcessedData/JHU' __C_JHU.TRAIN_LST = 'train.txt' __C_JHU.VAL_LST = 'val.txt' __C_JHU.VAL4EVAL = 'val_gt_loc.txt' __C_JHU.MEAN_STD = ([0.42968395352363586, 0.437104910612106...
from PyQt5 import uic from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QSplashScreen, QMainWindow from PyQt5.QtCore import QTime, QTimer, Qt, QThread, pyqtSignal from PyQt5 import uic import sys import time import logging logger = logging.getLogger("root") logger.setLevel(logging.DEBUG) class Main(QMainWin...
from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import app.routing application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter( app.routing.websocket_urlpatterns ) ), })
import numpy as np from matplotlib import pyplot as plb from utility import imageutil as im from utility import constants as ct from utility import util as ut def invert_gamma_of_image(image, gamma_params, callback=None): # requires parameter g, simply inverts gamma correction and returns new float64 image ...
students = {'Harry': 37.21, 'Berry': 37.21, 'Tina': 37.2, 'Akriti': 41, 'Harsh': 39} print(*sorted( [student for student, score in students.items() if score == (sorted(set(students.values()))[1])]), sep="\n")
from pybedtools import BedTool; import numpy as np; def generate_curve(bedfile, chromosome, region_start, region_stop): bedtool = BedTool(bedfile); region_of_interest = BedTool(chromosome + ' ' + str(region_start) + ' ' + str(region_stop), from_string=True); plot_region = region_of_interest.intersect(bed...
__author__ = 'luiz' import argparse from collectors.default_collector import DefaultCollector import os from multiprocessing import Pool, Semaphore, Manager import time from threading import Thread, Event import traceback def import_code(code, name, add_to_sys_modules=0): """ Import dynamically generated cod...
# coding: utf-8 # ### (Classroom Section: Project 4 Advanced Lane Finding) # ## L17: Undistort and Transform Quiz # ### My Solution: # # In an effort to reuse the Quiz code in my local Environment, I will copy some files from "Camera Calibration Quiz" into the local root where this notebook runs. # # **Note**: *...
import numpy as np import os import pickle import argparse import re ''' kopp14_fit_oceandynamics.py This runs the fitting stage for the ocean dynamics component of the Kopp14 workflow. Parameters: pipeline_id = Unique identifier for the pipeline running this code ''' def kopp14_fit_oceandynamics(pipeline_id): #...
from django.shortcuts import render from order.models import Order # Create your views here. def cart(request): """ See contents of cart also queries if the user exist otherwise creates one """ if request.user.is_authenticated: customer = request.user.customer order, created = Order.objec...
import io import base64 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def build_graph(data): img = io.BytesIO() plt.figure(figsize=(11,6.5)) subjects = list(data.keys()) def get_all_values(index, labels, data): all_values = [] for i in range(len(data)): ...
# coding=utf-8 if __name__ == '__main__': tagesmenus = [] while True: answer = raw_input("\nWas möchtest du machen?\n" "(1) Alle Gerichte anzeigen\n" "(2) Set (Vorspeise, Hauptspeise, Nachspeise) hinzufügen\n" "(3) Schre...
SOURCE = """/** * * Do something * * @dialect postgresql * @name get_contacts * @param contact_name: string - the name * @param contact_origin: string - the origin * @retmode tuples */ { select * from contacts where name=%(contact_name)s and origin=%(contact_origin)s ; """ FRAMES = []
# -*- coding: utf-8 -*- from odoo import models, fields, api class Contact(models.Model): # 3/25 建立表格欄位 圖片 名子 說明 _name = 'tekau_contacts' name = fields.Char(string='姓名') content = fields.Text(string='內容') phone = fields.Char(string='電話號碼') email = fields.Char(string="電子郵件") company_id =...
import torch.nn as nn import torch.nn.functional as F import torch dropout_value=0.02 class Unet(nn.Module): def __init__(self): super(Unet, self).__init__() self.convblockin = nn.Sequential( nn.Conv2d(in_channels=6,out_channels=3,kernel_size=(3,3),bias=False,padding=1), nn...
import psycopg2 import json import sys conn = psycopg2.connect(dbname="bookstore", user="bookstore", password="pass123", host="localhost") def fetch_by_isbn(isbn): cur = conn.cursor() cur.execute("SELECT * FROM books WHERE ISBN = (%s);", (isbn,)) res = cur.fetchone() if res is None: return Non...
// https://leetcode.com/problems/push-dominoes class Solution(object): def pushDominoes(self, dominoes): """ :type dominoes: str :rtype: str """ while(True): new = dominoes.replace('R.L', 'S') new = new.replace('.L','LL').replace('R.','RR') ...
from simbatch.core import core as batch import pytest import os @pytest.fixture(scope="module") def sib(): # TODO pytest-datadir pytest-datafiles vs ( path.dirname( path.realpath(sys.argv[0]) ) settings_file = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep + "config_tests.in...
import pytest from Threat_Vault import Client, antivirus_signature_get, file_command, dns_get_by_id, antispyware_get_by_id, \ ip_geo_get, ip_command, antispyware_signature_search, signature_search_results def test_antivirus_get_by_id(mocker): """ https://docs.paloaltonetworks.com/autofocus/autofocus-api/p...
import os, time import msgpack from hashlib import sha1 import functools import errno def mkdirs_safe(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise # Defaults to 15 days (1,296,000 sec) def c...
from submission import Submission class SilvestreSubmission(Submission): def run(self, s): """ :param s: input in string format :return: solution in integer format """ result = 0 char_list = list(s) char_list.append(char_list[0]) for i, char in enum...
import tensorflow as tf import numpy as np from tensorflow.contrib.rnn import LSTMCell, GRUCell import sys class character_rnn(object): ''' sample character-level RNN by Shang Gao parameters: - seq_len: integer (default: 200) number of characters in input sequence - first_read: intege...
import asyncio import aiohttp import time import logging from selenium import webdriver from selenium.webdriver.firefox import options from selenium.common.exceptions import NoSuchElementException try: import uvloop uvloop.install() except ImportError: pass logger = logging.getLogger("rend...
from locust import HttpUser, TaskSet, task, between class IOSUserBehavior(TaskSet): def on_start(self): r = self.client.get("/", auth=('yar', 333)) self.client.headers.update({'Authorization': r.request.headers['Authorization']}) def on_stop(self): self.client.get("/logout") @tas...
""" RMOption class represents a single option. It's better if you use the RMOptionHandler class, which automatically handles this options. """ class RMOption(object): def __init__(self, long_name: str, description: str, required: bool = False, default_value=None, short_name: str = None, ...
import time import numpy as np import torch from flatland.envs.observations import TreeObsForRailEnv from flatland.envs.predictions import ShortestPathPredictorForRailEnv from flatland.evaluators.client import FlatlandRemoteClient from flatland.utils.rendertools import RenderTool from torch import load ##############...
from collections import defaultdict from heapq import heapify, heappop class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: if not matrix: return 0 num_rows = len(matrix) num_cols = len(matrix[0]) indices = defaultdict(list) ...
from lxml import etree parser = etree.HTMLParser() tree = etree.parse('test.html', parser) titles = tree.xpath('/html/head/title') # This is a demo website if len(titles) > 0: print( titles[0].text ) html = ''' <div> <ul> <li class="item1"><a href="https://www.google.com"> 古哥 </a></li> <l...
import os import parser import unittest class TestParser(unittest.TestCase): def test_membros_ativos(self): self.maxDiff = None expected = { "reg": "128971", "name": "ACHILES DE JESUS SIQUARA FILHO", "role": "PROCURADOR DE JUSTICA", "type": "membro"...
from scrapy import log from scrapy.selector import HtmlXPathSelector from scrapy.contrib.spiders import SitemapSpider from walmartproducts.items import WalmartproductsItem class MySpider(SitemapSpider): name = 'spiderSM' log.ScrapyFileLogObserver(open('SiteMaplog.log','a'), level=log.INFO).start() handle_...
"""delete duplicate node exp: 1 1 2 3 3 1 2 3 """ class ListNode(object): def __init__(self, x): self.val = x self.next = None def delete_duplicate(head): cur = head while cur: while cur.next and cur.next.val == cur.val: cur.next = cur.next.next cur = cur.next # ...
# young 124ms, 166 n = int(input()) a=[] for i in range(1,n+1) : j = str(i) t = j.count('3') + j.count('6') + j.count('9') if t >0 : j = '-'*t print(j, end=' ')
import numpy as np import random from ..gui.Objects import Material, MAX_MEMBER_LENGTHS from ..lib.genotype import toGenotype, fromGenotype, stdbinToGray class Bridge(): def __init__(self, state, node_weight=10, street_weight=20): state = state.clone() street_nodes = [node for node in state.nodes...
import cv2 import numpy as np import time import datetime from config import conf import os img = cv2.imread(conf.sample_folder + 'slika2.png') img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # lower mask (0-10) lower_red = np.array([30,150,50]) upper_red = np.array([255,255,180]) mask = cv2.inRange(img_hsv, lower_red, ...
def solution(n): ans = 0 if n == 1 or n == 2: return 1 if n%2==0: return solution(n/2) return solution((n-1)/2) + 1
# Generated by Django 3.1.7 on 2021-03-19 05:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('news', '0003_users_last_login'), ] operations = [ migrations.RenameField( model_name='userchannel', old_name='channel_id', ...
from django.db import models # Create your models here. class Filier(models.Model): filier = models.CharField(max_length=80) def __str__(self): return self.filier class Students(models.Model): f_name = models.CharField(max_length=250) l_name = models.CharField(max_length=250) filier = mod...
from conans import ConanFile, AutoToolsBuildEnvironment, RunEnvironment, tools import os class PySideConan(ConanFile): name = "PySide" description = "PySide is a high dynamic-range (HDR) image file format developed by Industrial Light & " \ "Magic for use in computer imaging applications." ...
# Generated by Django 3.1.3 on 2020-11-16 00:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tickets', '0016_auto_20201116_0044'), ] operations = [ migrations.AlterField( model_name='seat', name='movie', ...
import os from setuptools import setup, find_packages # exec (open('version.py').read()) setup(name='stackview', version='0.0.1', description='Stack(img) for viewing slices of ndarrays w ndim > 2.', # url='https://github.com/maweigert/spimagine', author='Coleman Broaddus', author_email='...
to_int = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 } # IV -> smaller, larger -> return larger - smaller # XI -> larger, smaller -> return larger + smaller -> add the first, then # vv def roman_to_int(roman): if len...
import math import torch import torch.nn as nn import torch.nn.functional as F from utils import utils # pylint: disable=arguments-differ def initialize_weight(x): nn.init.xavier_uniform_(x.weight) if x.bias is not None: nn.init.constant_(x.bias, 0) class FeedForwardNetwork(nn.Module): def __...
# Schrijf (en test) de functie som() die 1 parameter heeft: getallenLijst. # Ga ervan uit dat dit een list is met integers. # De return-waarde van de functie moet de som (optelling) van de getallen in de lijst zijn! # Tip: bekijk nog eens de list-functies (Perkovic, blz. 28). def som(getallenLijst): totaal = 0 ...
#!/usr/bin/python3 import smtplib from string import Template from email.mime.base import MIMEBase from email import encoders import sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Function to read the contacts from a given contact file and return a # list of names and email a...
#!/usr/bin/env python3 from gzip import open import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import accuracy_score def prepare_array(filename, fraction): with open...
#Problem 2 lst = ["a", "b", "10", "bab", "a"] val = "a" def find_all(lst,val): newlst = [] for i in range(len(lst)): if lst[i] == val: newlst.append(i) #newlst += [i] print(newlst) (find_all(lst,val))
from django.urls import path, re_path from board.views import * from django.contrib import admin app_name = 'board' urlpatterns = [ path('', BoardView.as_view(), name='board'), path('<int:pk>', BoardViewDV.as_view(), name='details'), # Example: /board/add path('add/', BoardCreateView.as_view(), name="...
from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=T...
from CalvertScreen import Screen from CalvertObjects import * from CalvertGame import Game import random pygame.init() ### create screen actors = pygame.sprite.Group() scenery = pygame.sprite.Group() groups = [scenery,actors] screen_width = 700 screen_height = 500 screen = Screen(screen_width,screen_height...
from django.core.management import setup_environ import os import sys sys.path.append(os.path.dirname(__file__)) import settings setup_environ(settings) #==================================# from mybioregions.models import * from django.contrib.gis.geos import GEOSGeometry from django.contrib.auth.models i...
from sklearn.datasets import load_boston from dnpy.layers import * from dnpy.net import * from dnpy.optimizers import * from dnpy import metrics, losses # For debugging np.random.seed(1) def main(): # Get data X = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], ...
import gensim from gensim.corpora.wikicorpus import WikiCorpus from gensim.models import Phrases, TfidfModel from gensim.models.phrases import Phraser from gensim.test.utils import datapath from gensim.models.word2vec import Word2Vec, Text8Corpus import json import logging class ModelWord2Vec: """path è la stringa...
"""interface functions for model_fitting of CNNs""" from itertools import product from collections import OrderedDict from copy import deepcopy import time import json import numpy as np import h5py from .configs import cnn_opt, cnn_arch, cnn_init from .cnn import CNN from .training_aux import train_one_case, count_...
# -*- coding: utf-8 -*- ''' otsu.fun - SSWA Utils @version: 0.1 @author: PurePeace @time: 2020-01-07 @describe: a treasure house!!! ''' import time, datetime # way to return utInfo, decorator def messager(func): def wrapper(*args, **kwargs): data, message, info, status = func(*args,**k...
from flask import Flask, render_template, url_for, Response, request, redirect from os import path app = Flask(__name__) @app.route('/') def homepage(): return render_template('homepage.html') @app.route('/sketch/') def sketch(): return render_template('sketch.html') if __name__ == '__main__': app.run(de...
i = 0 # counter while i < 40: # loop to reach first 20 numbers only if i % 2 == 0: # in case if the reminder equal 0 the number will be even print(i) i = i + 1 # going to add 1 each time on i
import sys from fastNLP import Optimizer import torch as tc import torch.nn as nn import torch.optim as optim import numpy as np from config import logger class WarmAdam(optim.Optimizer): def __init__(self, params , d_model, n_warmup_steps , init_steps = 0 , step_size = 1): self.init_lr = np.power(d_model, -0.5) ...
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from gmuwork.shortcuts import quick_pfp1_file_reader import matplotlib.pyplot as plt from matplotlib import animation,rc from IPython.display import HTML, Image import numpy as np from sklearn.decomposition import PCA from gmuwork.shortcuts import...
#!/usr/bin/env python from itertools import product from combinatorics import combinator C = combinator([0,1,2,3,4,5,6,7,8,9],6) confs = [tuple(c) for c in C] squares = ["%02d"%(n**2) for n in range(1,10)] digit_pairs = [(int(c[0]),int(c[1])) for c in squares] def check(c1,c2): testc1 = c1 testc2 = c2 ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # class Solution: # def isPalindrome(self, head: ListNode) -> bool: # node = head # isPalindrom = True # # get all elements in array by trave...
# -*- coding: utf-8 -*- """ Created on Sat Dec 2 17:59:06 2017 @author: oliver.cairns """ import hashlib input_str = "yzbqklnj" input_str = "abcdef" num = "609043" def lowest_5_zero_num(input_str): num = -1 flag = True while flag: num += 1 num_string = str(num) test = hex(input...
# -*- coding: utf-8 -*- def insertion_sort(data): for index in range(len(data)-1): for index2 in range(index+1, 0, -1): if data[index2] < data[index2-1]: data[index2], data[index2-1] = data[index2-1], data[index2] else: break return data ####################################### # 사용! import random ...