content
stringlengths
5
1.05M
from __future__ import print_function import json import random import logging print('Loading function') logger = logging.getLogger() logger.setLevel(logging.INFO) def respond(err, res=None): return res def lambda_handler(event, context): print("Print Received event: " + json.dumps(event, indent=2)) ...
# Copyright (c) 2021 PaddlePaddle 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 appli...
import cv2 as cv import numpy as np titleWindow = 'Hit_miss.py' input_image = np.array(( [0, 0, 0, 0, 0, 0, 0, 0], [0, 255, 255, 255, 0, 0, 0, 255], [0, 255, 255, 255, 0, 0, 0, 0], [0, 255, 255, 255, 0, 255, 0, 0], [0, 0, 255, 0, 0, 0, 0, 0], [0, 0, 255, 0, 0, 255, 255, 0], [0,255, 0, 255, ...
import smart_imports smart_imports.all() settings = dext_app_settings.app_settings('PVP', BALANCER_SLEEP_TIME=5, BALANCING_TIMEOUT=5 * 60, BALANCING_MAX_LEVEL_DELTA=16, ...
from datetime import date a = int(input('Que ano quer analisar? Coloque 0 para analisar o ano atual: ')) if a == 0: a = date.today().year if a % 4 == 0 and a % 100 != 0 or a % 400 == 0: print('O ano {} é bissexto'.format(a)) else: print('O ano {} NÃO é BISSEXTO'.format(a))
from django.utils.text import slugify from dcim.models import Site from extras.scripts import * class MyScript(Script): class Meta: name = "Fix Site Slug" description = "updates all sites to use the lower case facility code as the site slug" commit_default = False def run(self, data,...
from unityagents import UnityEnvironment import numpy as np from dqn_agent import Agent from collections import deque import torch # Get the Unity environment env = UnityEnvironment(file_name="Banana_Windows_x86_64/Banana.exe") # Get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] en...
""" Mock plugin file for tests """ import numpy as np from batman.functions import Ishigami, Branin f_ishigami = Ishigami() f_branin = Branin() def f_snapshot(point): return np.array([42, 87, 74, 74])
# coding: utf-8 # Copyright (c) 2018 ubirch GmbH. # # 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 agr...
# country code used is alpha 3 country code currency_countrycode_mapping = {'AED':'ARE', 'AFN':'AFG', 'ALL':'ALB', 'AMD':'ARM', 'ANG':'ANT', 'AOA':'AGO', 'ARS':'ARG', 'AUD':'AUS', 'AWG':'ABW', 'AZN':'AZE', 'BAM':'BIH', 'BBD':'BRB', 'BDT':'BGD', 'BGN':'BGR', 'BHD':'BHR', 'BIF':'BDI', 'BMD':'BMU', 'BND':'BRN', 'BOB':'B...
from HiParTIPy.PtiCffi import pti,PTI import os class VecBuff: def __init__(self,size): self.nthreads = (int)(os.popen('grep -c cores /proc/cpuinfo').read()) print(self.nthreads) self.address = pti.cast("ptiValueVector *", PTI.malloc(self.nthreads * pti.sizeof(pti.new("ptiValueVector *"))))...
from Bio import SeqIO import sys # take the output of gffread and make a file with the longest isoforms genes = SeqIO.to_dict(SeqIO.parse(sys.argv[1],"fasta")) longest = {} for rec in genes: gene = genes[rec].description.split("=")[-1] if (gene not in longest) or (longest[gene][0] < len(rec)): longest[gene] = (le...
# -*- coding: utf-8 -*- # Copyright (c) 2021, trava and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class LabelPrinting(Document): def validate(self): self.validate_item() def validate_item(self): ...
from typing import Any, Optional import attr @attr.s(eq=False, frozen=True, slots=True) class Vertex: """Represents a vertex in a Knowledge Graph.""" name = attr.ib(type=str, validator=attr.validators.instance_of(str)) predicate = attr.ib( default=False, type=bool, validator=attr...
# wsdl.py - WSDLParser class, part of osa. # Copyright 2013 Sergey Bozhenkov, boz at ipp.mpg.de # Licensed under LGPLv3 or later, see the COPYING file. """ Conversion of WSDL documents into Python. """ from . import xmlnamespace from . import xmlparser from . import xmlschema from . import xmltypes from . import m...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from .multihead_attention import MultiheadAttention from .graphormer_layers import GraphNodeFeature, GraphAttnBias from .graphormer_graph_encoder_layer import GraphormerGraphEncoderLayer from .graphormer_graph_encoder import GraphormerGraphEncode...
# -*- coding: utf-8 -*- # Copyright (c) 2020 CPV.BY # LICENSE: Commercial # класс работы с локальной БД SQL # таблицы - GRUPPA, TOVAR, MOD, CASHIER, CLIENT import os from libs.base.lbsql import qsql import json import time from datetime import datetime from libs.applibs.programsettings import oConfig from kivy.con...
import logging from kazoo.client import KazooClient, KazooState from constants import zk_sequencer_root from strategy import SequenceStrategy class DistributedSequenceCoordinator(object): def __init__(self, zookeeper_connect, autoscaling_grp_name, strategy_name, instance_id, max_sequence_id, asg...
async def handleRequest(request): visitor_ip = request.headers.js_get('CF-Connecting-IP') console.log(visitor_ip) r = await fetch("https://api.ip.sb/geoip/" + visitor_ip) d = await r.json() d['time'] = Date.now() return __new__(Response(JSON.stringify(d), { 'headers' : { 'content-type' :...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`test_standard` ================== .. module:: test_standard :platform: Unix, Windows :synopsis: .. moduleauthor:: hbldh <henrik.blidh@nedomkull.com> Created on 2015-07-04, 12:00 """ from __future__ import division from __future__ import print_function f...
''' Convert CSV file to a basic ruleset package ''' import os import pathlib import re import argparse from numpy.core.numeric import full import pandas as pd from tqdm import tqdm TPL_RULENAME_CM = 'cm_%s' TPL_REGEXP_FILENAME = "resources_regexp_re%s.txt" TPL_USED_RES_FILENAME = "used_resources.txt" TPL_MATCHRULES_FI...
#!/usr/bin/env python3 import json import os print('Content-Type: text/html') print() payload = { # Question 1 'environment_variables': dict(os.environ), # Question 2 'query_parameter': os.environ['HTTP_USER_AGENT'], # Question 3 'browser_info': os.environ['HTTP_USER_AGENT'] } for section_ti...
import femagtools def create_fsl(): machine = dict( name="PM 130 L4", lfe=0.1, poles=4, outer_diam=0.04, bore_diam=0.022, inner_diam=0.005, airgap=0.001, stator=dict( num_slots=12, statorBG=dict( yoke_diam_ins=...
import sys class AutoIndent(object): def __init__(self, stream): self.stream = stream self.offset = 0 self.frame_cache = {} def indent_level(self): i = 0 base = sys._getframe(2) f = base.f_back while f: if id(f) in self.frame_cache: ...
""" Helper functions to query and send commands to the controller. """ import requests REQUESTS_TIMEOUT = 10 def status_schedule(token): """ Returns the json string from the Hydrawise server after calling statusschedule.php. :param token: The users API token. :type token: string :returns: Th...
""" A permutation of length n is an ordering of the positive integers {1,2,…,n}. For example, π=(5,3,2,1,4) is a permutation of length 5. Given: A positive integer n≤7. Return: The total number of permutations of length n, followed by a list of all such permutations (in any order). """ from typing import Sequence fro...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os import re import sys import struct from Peach.generator import Generator from Peach.Generators.dictionary impor...
def __sort_array(a_list): result = a_list for i in range(0, len(result) - 1, 1): for j in range(i + 1, len(result), 1): if result[i] > result[j]: result[i], result[j] = result[j], result[i] return result def find_the_pair_of_values(first_array, second_array): __so...
# -*- coding: utf-8 -*- import os import re import struct import sys from socket import inet_ntoa from lumbermill.BaseThreadedModule import BaseThreadedModule from lumbermill.utils.Decorators import ModuleDocstringParser @ModuleDocstringParser class NetFlow(BaseThreadedModule): r""" Netflow parser Decod...
class FilterModule(object): def filters(self): return { 'get_zone_interfaces': self.get_zone_interfaces, } def get_zone_interfaces(self, zones): dmz_lab_interfaces = list() home_interfaces = list() internet_interfaces = list() if 'multi-routing-...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Spyder Project Contributors # # Licensed under the terms of the MIT License # (see LICENSE.txt for details) # ----------------------------------------------------------------------------- # Standard ...
import serial # Serial port configuration ser = serial.Serial() ser.port = 'COM3' ser.baudrate = 4800 ser.open() # Send data continuously while ser.isOpen(): #print(ser.portstr) # check which port was really used ser.write(bytes("150", 'ascii')) # write a string #ser.close() # close ...
# Copyright (c) 2020, 2021, Oracle and/or its affiliates. # # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ # from utils import auxutil from setup import defaults class Config: version_tag = defaults.VERSION_TAG min_supported_version = defaults.MIN_SUP...
n = int(input()) for _ in range(n): c = 0 linha = input() esquerda = [] for x, n in enumerate(linha): if n == '<': esquerda.append(n) elif n == '>' and esquerda: esquerda.pop() c += 1 print(c)
# Copyright (c) 2015, # Philipp Hertweck # # This code is provided under the BSD 2-Clause License. # Please refer to the LICENSE.txt file for further information. import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) import unittest from testing import integration_t...
from setuptools import setup install_requires = [ # Pin deps for now, to be upgraded after tests are much expanded. 'Genshi==0.7', 'lxml==3.6.0', 'Pygments==1.4', 'python-dateutil==2.5.3', 'Twisted[tls]==16.4.0', 'klein', 'treq', 'attrs', ] extras_require = { 'testing': [ ...
import numpy as np class Settings: """ Class for different program settings. At the start these settings are loaded from predefined file. """ def __init__(self): """ This function has different properties: Attributes ---------- self.derivative_dx : float ...
import flax.linen as nn import jax.numpy as jnp from .config import Config from .wavenet import WaveNetBlock class DiffWave(nn.Module): """DiffWave: A Versatile Diffusion Model for Audio Synthesis. """ config: Config def setup(self): """Setup modules. """ config = self.config...
#!/usr/bin/env python3 # ============================================================== # author: Lars Gabriel # # runEVM.py: Run EVM for a set of partitions # ============================================================== import argparse import subprocess as sp import multiprocessing as mp import os import csv import ...
import regex as re def remove_feminine_infl(text): text = re.sub('(.*)/in(?!\w)', r'\1', text) text = re.sub('(.*)/n(?!\w)', r'\1', text) return text def remove_article(text): if not re.search('^ein\s+((für alle)|(paar))', text): text = re.sub('^(?:die|der|das|dem|den|ein|eine|einen|einem)\s+...
from typing import Text from ..request import get from ..Model.ApiModel import Channel from pydantic import BaseModel class all_channel(BaseModel): ch:list[Channel] def get_channel(channel_id:Text) -> Channel: """获取子频道信息""" channel = get(f"/channels/{channel_id}") channel_info = Channel(**channel) ...
# Standard lib imports import logging # Third party imports # None # Project level imports # None log = logging.getLogger(__name__) class UserInfo(object): def __init__(self, connection): """ Initialize a new instance """ self.conn = connection def whoami(self): "...
class Solution(object): def thirdMax(self, nums): n1 = n2 = n3 = None for e in nums: if e != n1 and e != n2 and e != n3: if n1 is None or e > n1: n1, n2, n3 = e, n1, n2 elif n2 is None or e > n2: n2, n3 = e, n2 ...
import http from flask import request from flask_restful import Resource, reqparse from models import User from utils.decorators import api_response_wrapper from utils.rate_limit import rate_limit from .login_service import generate_jwt_tokens parser = reqparse.RequestParser() parser.add_argument("email", help="Thi...
from numba import jit import math import numpy as _np from netket import random as _random class _HamiltonianKernel: def __init__(self, hamiltonian): self._hamiltonian = hamiltonian self._sections = _np.empty(1, dtype=_np.int32) self._hamconn = self._hamiltonian.get_conn_flattened ...
import pytest from data_structures.heap import Heap @pytest.fixture def base_heap(): heap = Heap() heap.push(1) heap.push(2) heap.push(3) heap.push(4) heap.push(5) return heap def test_heap_init(): basic_heap = Heap() init_list_heap = Heap([9, 8, 7, 5, 1, 2]) assert isinstanc...
import predict import cv2 import base64 import json def make_json(img, happy, confidence): # 인코딩된 스트링을 저장할 객체 encoded_string = None # 이미지 저장 cv2.imwrite('Cropped_image.jpg', img) # 이미지를 다시 열고 (이것은 대훈이가 이렇게 하는게 된다고 함 꼼수인듯 ㄱㅇㄷ) with open("Cropped_image.jpg", "rb") as image_file: encoding...
import CGIHTTPServer,BaseHTTPServer server_address = ('', 8000) handler = CGIHTTPServer.CGIHTTPRequestHandler httpd = BaseHTTPServer.HTTPServer(server_address, handler) print("server running on port %s" %server_address[1]) httpd.serve_forever()
# -*- coding: utf-8 -*- tipos = int(input()) quantidades = list(map(int, input().split())) print(min(quantidades))
import torch import torch.nn as nn def lerp_nn(source: nn.Module, target: nn.Module, tau: float): for t, s in zip(target.parameters(), source.parameters()): t.data.copy_(t.data * (1. - tau) + s.data * tau) def get_huber_loss(bellman_errors, kappa=1): be_abs = bellman_errors.abs() huber_loss_1 = ...
from app.drivers.mslookup import base from app.actions.mslookup import biosets as lookups from app.drivers.options import mslookup_options class BioSetLookupDriver(base.LookupDriver): outsuffix = '_setlookup.sqlite' lookuptype = 'biosets' command = 'biosets' commandhelp = ('Create SQLite lookup of mzM...
import asyncio import base64 import hashlib import hmac from http.cookies import SimpleCookie import json import urllib.request SALT = "datasette-auth-github" class BadSignature(Exception): pass class Signer: def __init__(self, secret): self.secret = secret def signature(self, value): ...
import requests import telebot import time url = 'https://api.github.com/orgs/JBossOutreach/repos' json_data = requests.get(url).json() numoflists = len(json_data) stars = 0 for i in range(numoflists): stars += json_data[i]['stargazers_count'] bot_token = '566958721:AAEVVrN8R5f0DfDW_pdxsekdpqo3C1Vs4ao' bot =...
# Copyright (c) Jean-Charles Lefebvre # SPDX-License-Identifier: MIT from sys import version_info if version_info < (3, 6): raise ImportError('fitdecode requires Python 3.6+') del version_info from .__meta__ import ( __version__, version_info, __title__, __fancy_title__, __description__, __url__, __li...
""" Python Template =============== python is a collection of python TEMPLATES. usage: >>> import python >>> help(python) """ __version__ = "0.0.1" from . import docstring # import docstring from the same directory as __init__.py
from dados import produtos, pessoas, lista print('-=-'* 20) print(f'{" MAP com listas ":=^40}') print(lista) # map() sempre recebe uma função como primeiro parâmetro. # map retorna sempre um iterador. nova_lista = map(lambda x: x * 2, lista) # utilizando o list comprehenson no lugar de map() nova_lista = [x * 2 for ...
from sectool.services.github import GitHub def test_make_url(): assert GitHub(user='japsu').make_owner_url('repos') == 'https://api.github.com/users/japsu/repos'
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/type/month.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from go...
### The Bat-Code ### import turtle as dark import math dark.width(8) dark.bgcolor("black") dark.color("#FDD017") zoom=30 dark.left(90) dark.penup() dark.goto(-7*zoom,0) dark.pendown() for xz in range(-7*zoom,-3*zoom,1): x=xz/zoom absx=math.fabs(x) y=1.5*math.sqrt((-math.fabs(absx-1))*math.fabs(3-absx)/((absx-...
# coding: utf-8 from dohq_teamcity.custom.base_model import TeamCityObject # from dohq_teamcity.models.license_key import LicenseKey # noqa: F401,E501 class LicenseKeys(TeamCityObject): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ ...
import re from oks import ok from config import THE def csv(src): for x,y in xy( # seperate line into independent and depednent variables data( # convert (some) strings to floats cols( # kill cols we are skipping rows( # kill blanks and comments ...
# Copyright 2017-present Open Networking Foundation # # 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 ag...
class Unit(object): def __init__(self, shortname, fullname): self._shortname = shortname self._fullname = fullname def shortname(self): return self._shortname def fullname(self): return self._fullname def __str__(self): return 'Unit(%s, %s)' % (self.shortname(...
""" Interface to run an experiment on Kernel Tuner """ from copy import deepcopy import numpy as np import progressbar from typing import Any, Tuple import time as python_time import warnings import yappi from metrics import units, quantity from caching import CachedObject record_data = ['mean_actual_num_evals'] de...
from django.contrib import admin from umap.models import Result, Race, Pmodel, Log class ResultInline(admin.TabularInline): fields = ["rank", "bracket", "horse_num", "horse_name", "sex", "age", "jockey_name", "weight", "finish_time", "time_lag", "odds", "prize"] model = Result readonly_fiel...
import cv2 import numpy as np import face_recognition as fr import serial from gpiozero import LED from numpy import savetxt from numpy import loadtxt inFace = "images/"+input("Enter path to Face: ") mode = input("Enter Mode [2 for rPI, 1 for arduino, 0 for null]: ") outFace = loadtxt("faEnc.csv", delimiter=",") imgT...
# Time: O(V+E) # Space: O(times) class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: import heapq graph = collections.defaultdict(list) for src, tgt, wt in times: graph[src].append([wt, tgt]) heap = [[0, K]] # time it took to ge...
import music21 as mus import numpy as np class NoteDistribution: ''' This class contains methods to get statistics about the notes in the melody of a song. ''' def __init__(self): pass @staticmethod def get_note_matrix(scores): ''' This method takes a list of scor...
#!/usr/bin/env python # -*- encoding: utf-8 """ Best-effort clean up of downloaded YouTube .srt subtitle files. """ import re import sys data = open(sys.argv[1]).read() # Now throw away all the timestamps, which are typically of # the form: # # 00:00:01,819 --> 00:00:01,829 align:start position:0% # data, _ = r...
import os import numpy as np from .dsl import dsnn
#--------------------------------------------------------------------------- # Copyright 2014 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 # ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from gym_minigrid.minigrid import * from gym_minigrid.register import register import numpy as np class FourRoomsSkillsEnv(MiniGridEnv): """ Classic 4 rooms gridworld environment. Can specify agent and goal position, if not it set at random. """ def ...
from tzwhere import tzwhere import datetime import unittest class LocationTestCase(unittest.TestCase): TEST_LOCATIONS = ( ( 35.295953, -89.662186, 'Arlington, TN', 'America/Chicago'), ( 33.58, -85.85, 'Memphis, TN', 'America/Chicago'), ( 61.17, ...
class Solution: def __init__(self, string: str): self.string = string def toQuestion(self): pass def main(): givenString1 = Solution("enter_string") print(givenString1.toQuestion()) givenString2 = Solution("enter_2nd_string") print(givenString2.toQuestion()) if __...
import efficientnet.tfkeras from tensorflow.keras.models import load_model from tensorflow import nn from tensorflow.keras.backend import shape from tensorflow.keras.layers import Dropout import segmentation_models as sm import tf2onnx import onnxruntime as rt import tensorflow as tf class FixedDropout(Dropout): ...
from PyQt5 import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from deritradeterminal.util.deribit_api import RestClient from deritradeterminal.managers.ConfigManager import ConfigManager class PositionsUpdateThread(QThread): signeler = pyqtSignal(int,str,str,str,str,str,s...
import os import datetime import re import paho.mqtt.client as mqtt import json import yaml from argparse import ArgumentParser def args(): p = ArgumentParser() p.add_argument("--secrets", '-s', action="store", type=str, help='Transfer specified file as secrets.json') p.add_argument("--ignore-retained", '-...
""" manhattan.py Minor Programmeren, Programmeertheorie, Chips & Circuits Misbaksels: Lisa Eindhoven, Sebastiaan van der Laan & Mik Schutte These functions calculate the (minimum/maximum) manhattan distance between (a multitude of) two sets of coordinates. Use min/max_net for the determined shortest distance, use mi...
#!/usr/bin/env python # -*- coding:utf-8 -*- import logging import json import os import shutil import numpy as np from keras.callbacks import EarlyStopping from dde.cnn_model import build_model, train_model, reset_model, save_model, write_loss_report from dde.input import read_input_file from dde.molecule_tensor im...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-05-30 11:38 from __future__ import unicode_literals import consent.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('consent', '0020_auto_20170530_1615'), ] operations = [ ...
import unittest import math import io from pathlib import Path import vcfpy from cerebra.germline_filter import write_filtered_vcf from cerebra.utils import GenomePosition, GenomeIntervalTree class GermlineFilterTestCase(unittest.TestCase): @classmethod def setUpClass(self): self.data_path = Path(__f...
import hashlib import threading readlock = threading.Lock() writelock = threading.Lock() def get_hash(data): if type(data) != bytes: # wierd hack # be warned data = data.encode('utf-8') gfg = hashlib.sha3_256() gfg.update(data) return gfg.hexdigest() empty_hash = get_hash(''...
# coding: utf-8 """ NRF NFDiscovery Service NRF NFDiscovery Service. © 2020, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. # noqa: E501 The version of the OpenAPI document: 1.1.0.alpha-4 Generated by: https://openapi-generator.tech """ from __future_...
import numpy as np from pandas import Categorical, Series import pandas._testing as tm class TestUnique: def test_unique_data_ownership(self): # it works! GH#1807 Series(Series(["a", "c", "b"]).unique()).sort_values() def test_unique(self): # GH#714 also, dtype=float ser = Se...
#!/bin/python3 # from matplotlib import colors, cm # from matplotlib.ticker import PercentFormatter # import matplotlib.pyplot as plt from scipy import stats from subprocess import Popen, PIPE import numpy as np import pathlib, json, glob, os import random import math ## Commented out counters are zero at the 99th pe...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^pool/(?P<pk>[0-9a-zA-Z\/]+)/$', views.UserRedirectView.as_view(), name='pool'), url(r'^pool/(?P<pk>[\d\w_]+)$', views.pool_fix, name='pool_fix'), #allow decimal and words only. ]
#!/usr/bin/env python3 if not __name__ == "__main__": exit("You should not run this application as a library!") import pygame import tkinter as tk from tkinter import filedialog FPS = 30 FONT_SIZE = 18 OUTLINE_WIDTH = 2 UI_SPACING = 10 COLOR_BUTTON_SIZE = 22 pygame.init() window...
# Gradient descent will be performed for Rosenbrock function: (a-x)**2+ b(y-x**2)**2 def process(numIter, alpha, x, y, a, b): history_arr = [] history_arr.append((x, y, get_f(x, y, a, b))) for i in range(numIter): x -= alpha * get_delta_x(x, y, a, b) y -= alpha * get_delta_y(x, y, a, b) ...
import cv2 import numpy as np import time video = cv2.VideoCapture(0, cv2.CAP_DSHOW) time.sleep(3) for i in range(60): check, background = video.read() background = np.flip(background, axis=1) while(video.isOpened()): check, img = video.read() if check == False: break img = np.f...
import os import pynbody import numpy as np import tangos import tangos.input_handlers.pynbody from tangos import testing, input_handlers, tools, log, parallel_tasks import numpy.testing as npt def _get_gadget_snap_path(snapname): return os.path.join(os.path.dirname(__file__),"test_simulations", ...
import torch, numpy as np, warnings, pandas as pd, collections, torch.nn.functional as F from torch.utils.data import DataLoader from pytorch_lightning import Trainer from pytorch_lightning.callbacks import LearningRateMonitor from ..util import (_LitValidated, empty_cache_on_exit, create_matrix, cr...
import re s = 'life is short, i use python' res = re.search('life(.*)python', s) print(res) # <re.Match object; span=(0, 27), match='life is short, i use python'> print(res.group()) # life is short, i use python print(res.group(0)) # life is short, i use python --> 0 代表完整匹配结果 print(res.group(1)) # is short, i use ...
BBBB BBBBBBBBBBBBBBBBBBBBBBB BB BBBB BBBBBBB BBBBBBBBBBBBBBBBBBBBBBBB BBBBBBB BBB BBBB BB BBBBBBB XXXX XXXXXXXXXXXXXXXXXXX BBBBBBB BBBBBBBBBBBBBBBBBBBBBBBB XXXXXX BBBBBB
from ecoxipy.pyxom.output import PyXOMOutput from ecoxipy.decorators import markup_builder_namespace from ecoxipy.html import HTML5_ELEMENT_NAMES from tests.performance.ecoxipy_base import create_testdoc create_testdoc = markup_builder_namespace( PyXOMOutput, '_b', *HTML5_ELEMENT_NAMES)(create_testdoc) create_...
from .models import SocialLink, MainMenuPoint def load_settings(request): """The processor for implements social_links and menu options in the context of every page on the site""" return { 'social_links': SocialLink.objects.all(), 'main_menu': MainMenuPoint.objects.all(), }
import math import os import shutil import socket import stat import subprocess import textwrap import time from aioredis.log import logger REDIS_SERVER_EXEC = os.environ.get('REDIS_SERVER_EXEC') or 'redis-server' REDIS_SLOT_COUNT = 16384 _MAX_RETRY_ERRORS = 4 _ATTEMPT_INTERVAL = 0.3 class TestCluster: """This ...
from pyhf.parameters.paramsets import ( paramset, unconstrained, constrained_by_normal, constrained_by_poisson, ) from pyhf.parameters.utils import reduce_paramsets_requirements from pyhf.parameters.paramview import ParamViewer __all__ = [ 'paramset', 'unconstrained', 'constrained_by_normal...
import time import datetime print("Please type your text after 3 seconds") print("3") time.sleep(1) print("2") time.sleep(1) print("Go!") time.sleep(0.2) before = datetime.datetime.now() text=input("Type here:") after = datetime.datetime.now() speed = after - before seconds = round(speed.total_seconds(),2)...
import pygments, markdown, os from flask import Flask, flash, redirect, render_template, render_template_string, request, url_for, send_from_directory from flask import current_app as app from flask_flatpages import FlatPages, pygmented_markdown, pygments_style_defs from flask_mail import Mail, Message from .forms.pagi...
import json import kenlm from tqdm import tqdm model = kenlm.Model("../es.arpa.bin") def get_perplexity(doc): doc_log_score, doc_length = 0, 0 for line in doc.split("\n"): log_score = model.score(line) length = len(line.split()) + 1 doc_log_score += log_score doc_length += le...