content
stringlengths
0
894k
type
stringclasses
2 values
import pytest from dynaconf import LazySettings from dynaconf.loaders.yaml_loader import load, clean settings = LazySettings( NAMESPACE_FOR_DYNACONF='EXAMPLE', ) YAML = """ # the bellow is just to ensure `,` will not break string YAML a: "a,b" example: password: 99999 host: server.com port: 8080 service:...
python
# cls=20, base yolo5 import torch import torch.nn as nn import common as C from torchsummary import summary class YOLOV4(nn.Module): def __init__(self): super(YOLOV4, self).__init__() self.input = nn.Sequential( C.Conv(3, 32, 3, 1, mish_act=True), ) self.group0 = nn....
python
import onnxruntime as ort import numpy as np from onnxruntime_extensions import get_library_path # python implementation for results check def compare(x, y): """Comparison helper function for multithresholding. Gets two values and returns 1.0 if x>=y otherwise 0.0.""" if x >= y: return 1.0 els...
python
from itertools import permutations from pytest import raises import math import networkx as nx from networkx.algorithms.matching import matching_dict_to_set from networkx.utils import edges_equal class TestMaxWeightMatching: """Unit tests for the :func:`~networkx.algorithms.matching.max_weight_matching` func...
python
from unittest import TestCase from src import utils class TestGetLoggerName(TestCase): def test_get_logger_name(self): logger_name = utils.get_logger_name(self.__class__) self.assertEqual("TesGetLogNam", logger_name) class TestGetProxyPort(TestCase): def test_get_proxy_port(self): ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2015-08-24 12:46:36 # @Author : LiangJ import base64 import json from time import time import tornado.gen import tornado.web from BeautifulSoup import BeautifulSoup from sqlalchemy.orm.exc import NoResultFound from tornado.httpclient import HTTP...
python
# -*- coding: utf-8 -*- """ Created on Sat Jan 20 11:27:20 2018 @author: DrLC """ import pandas import math import nltk import re import gzip, pickle import matplotlib.pyplot as plt def load_csv(path="test.csv"): return pandas.read_csv(path, header=None) def load_class(path="classes.t...
python
import time import struct import sys import os import re import threading from functools import partial import wx import wx.lib.newevent as NE from spidriver import SPIDriver PingEvent, EVT_PING = NE.NewEvent() def ping_thr(win): while True: wx.PostEvent(win, PingEvent()) time.sleep(1) class He...
python
#!/usr/bin/python """ To add users and see their passwords """ import sqlite3 from passlib.hash import pbkdf2_sha256 conn = sqlite3.connect('DB.db', check_same_thread=False) c = conn.cursor() c.execute('''CREATE table if not exists LOGIN(unix real, username TEXT, password TEXT, hash TEXT)''') print "Opened database...
python
import datetime class BaseQuery(object): supports_rolling = False supports_isolated_rolling = False def __init__(self, query_name, client, vars, log): self.log = log self.query_name = query_name self.client = client self.vars = vars self.result = None self....
python
import tensorflow as tf hello = tf.constant('Hello, TF!') mylist = tf.Variable([3.142,3.201,4.019],tf.float16) mylist_rank = tf.rank(mylist) myzeros = tf.zeros([2,2,3]) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) print(sess.run(myzeros)) print(sess.run(mylist)...
python
# -*- coding: utf-8 -*- """ .. module:: NamedOpetope :synopsis: Implementation of the named approach for opetopes .. moduleauthor:: Cédric HT """ from copy import deepcopy from typing import ClassVar, Dict, List, Optional, Set, Tuple, Union from opetopy.common import * class Variable: """ A variable is...
python
# -*- coding: utf-8 -*- from flask import Flask # 引入 flask from flask import redirect from flask import render_template from flask import url_for from flask_cors import CORS from config import GlobalVar app = Flask(__name__, template_folder=GlobalVar.BASE_DIR + '/templates') # 实例化一个flask 对象 CORS(app) ...
python
# Copyright 2013 Red Hat, Inc. # 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...
python
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import re import os from urllib.parse import urljoin from datetime import datetime from bs4 import BeautifulSoup from ferenda import util from ferenda import Do...
python
# -*- coding: utf-8 -*- # Copyright 2018 IBM. # # 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 agre...
python
# Generated by Django 3.0.5 on 2020-04-19 04:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('spectroscopy', '0001_initial'), ] operations = [ migrations.AlterField( model_name='spectrophotometer', name='produc...
python
order = [ 'artellapipe.tools.outliner.widgets.buttons', 'artellapipe.tools.outliner.widgets.items' ]
python
#!/usr/bin/env python # Copyright 2020 T-Mobile, USA, 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 by applicabl...
python
import re from urllib.parse import urlsplit from bs4 import BeautifulSoup from .base_fetcher import BaseFetcher def clean_text(tag): text = tag.find("pre").prettify()[5:-6].replace("<br/>", "\n").replace(u'\xa0', ' ') # print('text', repr(text), repr(tag.find("pre").get_text())) return text ...
python
from mltoolkit.mldp import Pipeline from mltoolkit.mldp.steps.formatters import PyTorchFormatter class PyTorchPipeline(Pipeline): """ Addresses the issue associated with processes that put PyTorch tensors to a Queue object must be alive when the main processes gets/requests them from the Queue. Format...
python
import os import sys sys.path.append('../../') from dquant.markets._binance_spot_rest import Binance from dquant.markets._bitfinex_spot_rest import TradingV1 # from dquant.markets._huobi_spot_rest import HuobiRest from dquant.markets._okex_spot_rest import OkexSpotRest from dquant.markets.market import Market from dqua...
python
# Face.py - module for reading and parsing Scintilla.iface file # Implemented 2000 by Neil Hodgson neilh@scintilla.org # Released to the public domain. # Requires Python 2.5 or later def sanitiseLine(line): if line[-1:] == '\n': line = line[:-1] if line.find("##") != -1: line = line[:line.find("##")] line = line....
python
from setuptools import setup from setuptools_rust import RustExtension, Binding def read(f): return open(f, encoding='utf-8').read() setup( name="PyValico", version="0.0.2", author='Simon Knibbs', license='MIT', url='https://github.com/s-knibbs/pyvalico', author_email='simon.knibbs@gmail...
python
import matplotlib.pyplot as plt import numpy as np import csv markers = { 'heuristic': { 'timestamps': [], 'repl': [], 'repl_err': [], 'cost': [], 'cost_err': [], 'migr': [], 'migr_err': [], 'drop': [], 'drop_err': [], 'effc': [], 'effc_err': [] }, 'optimal': { 'timestamps': [], 'repl': [], 'repl_err': [], 'co...
python
# coding: utf-8 ''' =============================================================================== Sitegen Author: Karlisson M. Bezerra E-mail: contact@hacktoon.com URL: https://github.com/hacktoon/sitegen License: WTFPL - http://sam.zoy.org/wtfpl/COPYING =============================================================...
python
from configuration import configuration, dbName, debugEverythingNeedsRolling from optionChain import OptionChain from statistics import median from tinydb import TinyDB, Query import datetime import time import alert import support class Cc: def __init__(self, asset): self.asset = asset def findNew(...
python
"""Plotting Module.""" from scphylo.pl._data import heatmap from scphylo.pl._trees import clonal_tree, dendro_tree, networkx_tree, newick_tree __all__ = (heatmap, clonal_tree, dendro_tree, networkx_tree, newick_tree)
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-03-05 02:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('storehouse', '0002_supplier'), ] operations = [ migrations.CreateModel( ...
python
import json from pathlib import Path from types import SimpleNamespace from typing import NamedTuple, Any, Optional from flask.testing import FlaskClient from numpy.testing import assert_almost_equal from osgeo_utils.auxiliary.base import PathLikeOrStr test_env = SimpleNamespace() test_env.root = Path('.') test_env....
python
#!/usr/bin/python import smtplib import subprocess import urllib2 from email.mime.text import MIMEText smtp_address="YOUR SMTP LOGIN" sender="YOUR SMTP LOGIN " receiver="YOUR EMAIL DESTINATION" password="YOURU SMTP PASSWORD" uptime = subprocess.check_output('uptime') ip_ext = urllib2.urlopen("http://ifconfig.me/i...
python
from scipy.stats import norm import math def dice_test(stat, alfa, mode_speed): # add parametrs for normal distribution if mode_speed == "plt_6": critical_const = norm.ppf(alfa, loc=0.2700502, scale=math.sqrt(0.0002832429)) p_value = norm.cdf(stat, loc=0.2700502, scale=math.sqrt(0.0002832429)) ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from clickhouse_mysql.observable import Observable class Reader(Observable): """Read data from source and notify observers""" converter = None event_handlers = { # called on each WriteRowsEvent 'WriteRowsEvent': [], # called on each...
python
""" Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities find o...
python
import setuptools setuptools.setup( name="confluent_schema_registry_client", version="1.1.0", author="Tom Leach", author_email="tom@gc.com", description="A simple client Confluent's Avro Schema Registry", license="MIT", keywords="confluent schema registry client avro http rest", url="ht...
python
#!/usr/bin/env python2 """ Dump ranks into a JS file, to be included by index.html. The JS file contains a global "raw_data" object, with fields: - contests: list of included contests. Each is an object with: - name: name of the contest. - tasks: list of tasks to include in this contest. - scores: map each use...
python
"""Responses provided by the iov42 platform.""" import json from dataclasses import dataclass from typing import List from typing import Union from ._entity import Identifier from ._request import Request @dataclass(frozen=True) class BaseResponse: """Base class for successful platform responses.""" request...
python
# -*- coding:utf-8 -*- __author__ = 'shichao' import platform import tensorflow as tf import numpy as np import time def iterator_demo(): ''' python iterator demo :return: ''' class numIter: # def __init__(self, n): self.n = n def __iter__(self): self.x = ...
python
from __future__ import absolute_import, division, print_function, unicode_literals import sys from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QMessageBox, QFileDialog, QGridLayout, QHBoxLayout, \ QVBoxLayout, QGroupBox, QCheckBox, QPushButton, QAction from PatchEdit impor...
python
import typer INFO = typer.style("INFO", fg=typer.colors.GREEN) + ": " HELP = typer.style("HELP", fg=typer.colors.BLUE) + ": " FAIL = typer.style("FAIL", fg=typer.colors.RED) + ": " SUCCESS = typer.style("SUCCESS", fg=typer.colors.BLUE) + ": " typer.echo(f"{INFO} Importing modules, please wait") import os im...
python
#!/usr/bin/env python3.7 # Copyright 2021 DataStax, 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
python
import torch import onnx from pathlib import Path import sys def convert2onnx(model_path,input_size,out_path=None): if out_path is None: out_path=Path(model_path).with_suffix('.onnx') model=torch.load(model_path) out_path=export2onnx(model,input_size,out_path) return out_path ...
python
from caffe2.python import core import numpy as np class ParameterTags(object): BIAS = 'BIAS' WEIGHT = 'WEIGHT' COMPUTED_PARAM = 'COMPUTED_PARAM' class ParameterInfo(object): def __init__( self, param_id, param, key=None, shape=None, length=None, gra...
python
# Criar e modificar arquivos txt ''' 'r' = Usado somente para ler algo 'w' = Usado somente para escrever algo 'r+' = Usado para ler e escrever algo 'a' = Usado para acrescentar algo ''' numeros = [0, 15, 10, 20, 15, 45] # Criar um arquivo e colocar as informações da lista numeros dentro dele with open('numeros.txt...
python
""" Copyright Tiyab KONLAMBIGUE """ from gce import client import logging import time from model import job as jobmodel import configuration JSON_KEY_FOLDER = configuration.JSON_KEY_FOLDER # Google instance image project configs IMAGES_PROJECT = configuration.IMAGES_PROJECT class instance(): GCE_TERMINATED_STAT...
python
import datapackage from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url dep_prefix = 'dependency://' parameters, dp, res_iter = ingest() url = parameters['url'] if url.startswith(dep_prefix): dependency = url[len(dep_prefix):].strip() url = get_dependency_datapackage_url(de...
python
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from functools import reduce import operator import math import dolfin as dl import mshr def sort_points_in_anti_clockwise_order(coords): coords=coords.T center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coo...
python
from fractions import Fraction from src.seq import fibonacci, stern_diatomic_seq, fib_seq, stern_brocot from src.graph import stern_brocot_graph from itertools import islice import pytest def test_returns_first_5_numbers_of_stern_brocot(): assert take(stern_brocot, 5) == [ Fraction(1, 1), Fraction...
python
# Copyright 2020 Thiago Teixeira # # 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 writin...
python
from datetime import datetime from importers.e_trac_importer import ETracImporter from importers.nmea_importer import NMEAImporter from pepys_import.core.formats import rep_line def test_nmea_timestamp_parsing(): parse_timestamp = NMEAImporter.parse_timestamp # Invalid day in date result = parse_timesta...
python
from flask_wtf import FlaskForm from wtforms import IntegerField from wtforms import SelectField from wtforms import SubmitField from wtforms import StringField from wtforms import FileField from wtforms import SelectField from wtforms import PasswordField from wtforms.validators import Email, Length, Required from wtf...
python
from .serializers import User
python
""" Other plotting routines outside of matplotlib """ import matplotlib.transforms as transforms import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib.lines import Line2D import matplotlib.dates as mdates from matplotlib import collections from matplotlib.ticker impo...
python
import win32gui from src.services.window_managers.base_window_manager import WindowTitleManager class WindowsWindowManager(WindowTitleManager): def fetch_window_title(self) -> str: window_in_focus = win32gui.GetForegroundWindow() return win32gui.GetWindowText(window_in_focus)
python
import requests from bs4 import BeautifulSoup LIMIT = 50 URL = f"https://www.indeed.com/jobs?q=python&limit={LIMIT}" def _check_has_first_page_end() -> bool: """Check if the first page has a link to the last page""" first_response = requests.get(URL) soup = BeautifulSoup(first_response.text, "h...
python
from django.contrib import admin from django.urls import include, path from accounts.author.api import ( ForgetPasswordView, LoginAuthorAPIView, RegisterAuthorView, ) from accounts.editor.api import ( ForgetEditorPasswordView, LoginEditorAPIView, RegisterEditorView, ) from accounts.reviewer.api...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Useful functions for Counter manipulation. """ from collections import Counter def scale(cntr, factor): cntr_ = Counter() for key, value in cntr.items(): cntr_[key] = value * factor return cntr_ def normalize(cntr): return scale(cntr, 1./sum(...
python
# Copyright 2017-2018 The Open SoC Debug Project # # 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...
python
from __future__ import absolute_import import os.path import sys import threading import typing import attr from ddtrace.internal import compat from ddtrace.internal import nogevent from ddtrace.internal.utils import attr as attr_utils from ddtrace.internal.utils import formats from ddtrace.profiling import collecto...
python
""" Added dag name column to executions Revision ID: e937a5234ce4 Revises: a472b5ad50b7 Create Date: 2021-02-25 12:14:38.197522 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "e937a5234ce4" down_revision = "a472b5ad50b7" branch_labels = None depends_on = None ...
python
# Generated by Django 3.1 on 2020-08-05 10:07 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('website', '0010_auto_20200804_1433'), ] operations = [ migrations.AlterModelOptions( name='userplugin', options={'ordering': (...
python
from pathlib import Path def findFullFilename(path, pattern): filenameGenerator = Path(path).glob(pattern) firstPath = next(filenameGenerator, None) if firstPath is None: return None return firstPath.name def findPywFilenameHere(pattern): return findFullFilename(".", f"{pattern}*...
python
from heuristicSearch.planners.astar import Astar from heuristicSearch.envs.env import GridEnvironment from heuristicSearch.graph.node import Node from heuristicSearch.envs.occupancy_grid import OccupancyGrid from heuristicSearch.utils.visualizer import ImageVisualizer from heuristicSearch.utils.utils import * import m...
python
#! /usr/bin/env python from pathlib import Path import re import uxn import sys token_prog = re.compile(r"\s*(\)|\S+)") line_comment_prog = re.compile(r".*") string_prog = re.compile(r".*?(?<!\\)\"") fixed_prog = re.compile(r"(-|\+)?\d+\.\d+") prefix_chars = '%:.;,@&|$#~\'"' def eprint(s): sys.stderr.write(f"{...
python
# Python3 program for Painting Fence Algorithm # optimised version # Returns count of ways to color k posts def countWays(n, k): dp = [0] * (n + 1) total = k mod = 1000000007 dp[1] = k dp[2] = k * k for i in range(3,n+1): dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])...
python
""" Manipulate Excel workbooks. """ from datetime import datetime import os from openpyxl import Workbook from openpyxl.styles import NamedStyle, Font, Border, Side, PatternFill from trellominer.api import trello from trellominer.config import yaml class Excel(object): def __init__(self): self.config =...
python
# -*- coding: utf-8 -*- """ This is the Keras implementation for the GermEval-2014 dataset on NER This model uses the idea from Collobert et al., Natural Language Processing almost from Scratch. It implements the window approach with an isolated tag criterion. For more details on the task see: https://www.ukp.tu-dar...
python
import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = Cling(get_wsgi_application())
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: fabric_next.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _r...
python
import torch as th import numpy as np from gym import Env from gym.spaces import Discrete, MultiDiscrete __all__ = [ "MatrixGameEnv" ] class MatrixGameEnv(Env): def __init__(self, matrices, reward_perturbation=0, rand: th.Generator = th.default_generator): super().__init__() matrices ...
python
from __future__ import division, absolute_import, print_function import sys if sys.version_info < (3,): range = xrange else: unicode = str import os from matplotlib import rc from matplotlib import rcParams font_size=14 rcParams["backend"] = "PDF" rcParams["figure.figsize"] = (4, 3) rcParams["font.family"] = ...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
python
# 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 applicable law or agreed to in...
python
#!/usr/bin/env python3 import argparse import sys import logging from pathlib import Path from capanno_utils.validate import * from capanno_utils.validate_inputs import validate_inputs_for_instance from capanno_utils.helpers.validate_cwl import validate_cwl_tool from capanno_utils.helpers.get_paths import get_types_fr...
python
_base_ = [ '../../_base_/models/vision_transformer/vit_large_p16_sz224.py', '../../_base_/datasets/imagenet/swin_sz384_8xbs64.py', '../../_base_/default_runtime.py', ] # model model = dict(backbone=dict(img_size=384)) # data data = dict(imgs_per_gpu=64, workers_per_gpu=6) # additional hooks update_interv...
python
from rest_framework import serializers from core.models import Link, Comment class LinkSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Link class CommentSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Comment
python
# Generated by Django 3.2.4 on 2021-06-23 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('timewebapp', '0044_alter_settingsmodel_first_login'), ] operations = [ migrations.AlterField( model_name='settingsmodel', ...
python
import pytest import os @pytest.mark.processor("gpu") @pytest.mark.model("placeholder") @pytest.mark.skip_cpu @pytest.mark.skip_py2_containers def test_placeholder(): pass
python
#!/usr/bin/env python ''' Experimental viewer for DAVIS + OpenXC data Author: J. Binas <jbinas@gmail.com>, 2017 This software is released under the GNU LESSER GENERAL PUBLIC LICENSE Version 3. Usage: Play a file from the beginning: $ ./view.py <recorded_file.hdf5> Play a file, starting at X percent: $ ./view.py...
python
from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from pages.top_bars.top_navigate_bar import TopNavigateBar class TemplatesPage(TopNavigateBar): """ Templates page - contains variety of templates to select """ _TEMPLATES_BLOCK = (By.CSS_SELECTOR, "#templ...
python
#Hall bar geometry device. Measurements have r_xx and/or r_xy import numpy as np import matplotlib.pyplot as plt import warnings from scipy.signal import savgol_filter from pylectric.analysis import mobility from scipy import optimize as opt class Meas_GatedResistance(): """Class to handle a single sweep of raw da...
python
import pyautogui import time while True: initial_mouse = pyautogui.position() time.sleep(0.5) final_mouse = pyautogui.position() print(initial_mouse) print(final_mouse) if initial_mouse != final_mouse: pyautogui.hotkey("alt","tab") else: exit
python
''' Crie um programa: Leia o nome de um aluno leia duas notas do aluno guarde em uma lista composta no final mostre: Um boletim contendo: A média de cada um permita que o usuário possa mostrar as notas de cada aluno individualmente ''' alunos = list() while True:...
python
""" pyTRIS ------ pyTRIS - a simple API wrapper for Highways England's WebTRIS Traffic Flow API. """ from .api import API from . import models __all__ = ['API']
python
# -*- coding: utf-8 -*- """ created by huash06 at 2015-04-15 08:45 Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. 如果是求不连续的字串 方法1: 令f(i,j)表示s[i:j+1]的最长回文的长度 if s[i]==s[j]: f(i,j) = f(i...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 31 13:10:45 2018 @author: aloswain """ from datetime import datetime import backtrader as bt class SmaCross(bt.SignalStrategy): def __init__(self): sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30) crossover = bt.ind.Cr...
python
''' Algoritmo de Prim 1. T ← vazio; 2. V' ← {u}; 3. para-todo v E V – V' faça 4. L(v) ← peso ({u,v}); 5. fim-para-todo 6. enquanto V' != V faça 7. ache um vértice w tal que L(w) = min {L(v) | v E V-V'}; 8. u = o vértice de V', ligado a w, representando a aresta com o menor custo; 9. e = {u,w}; 10...
python
#! /usr/bin/python from pylab import * from sys import argv,exit,stdout import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline from scipy import interpolate import numpy as np from finite_differences_x import * from interp import * def read_EFIT(EFIT_file_name): EFITdict = {} f = open(...
python
# from __future__ import absolute_import from abstractions.recognition import DistanceEstimator import numpy from typing import List class NumpyDistanceEstimator(DistanceEstimator): def distance(self, face_features_we_have : [bytes], face_feature_to_compare ) -> List[float]: if len(face...
python
import json import os import random import sqlite3 import urllib import requests from flask import Flask app = Flask(__name__) def get_cursor(): connection = sqlite3.connect("database.db") c = connection.cursor() return c USER_ID = 1 def init_db(): c = get_cursor() c.execute(""" CREATE T...
python
####################################################################### ### Script for Calling Plotting Scripts and Merging the Plots ### ####################################################################### import sys current_path = sys.path[0] ex_op_str = current_path[current_path.index('progs')+6: current_p...
python
from heapq import heappush, heappop, heapify import itertools class Queue: def __init__(self): self.q = [] def enqueue(self, element): self.q.append(element) def dequeue(self): return self.q.pop(0) def is_empty(self): return len(self.q) == 0 def front(self): return self.q[0] class DisjointSets: d...
python
# import pytest # from ..accessor import session # @pytest.mark.skip(reason="initial run on gh actions (please remove)") # def test_session(): # """ # tests that a session can be created without error # """ # with session() as db: # assert db
python
""" This file builds Tiled Squeeze-and-Excitation(TSE) from paper: <STiled Squeeze-and-Excite: Channel Attention With Local Spatial Context> --> https://arxiv.org/abs/2107.02145 Created by Kunhong Yu Date: 2021/07/06 """ import torch as t def weights_init(layer): """ weights initialization Args : --layer: one la...
python
from typing import Iterable from eth2spec.test.context import PHASE0 from eth2spec.test.phase0.genesis import test_initialization, test_validity from gen_base import gen_runner, gen_typing from gen_from_tests.gen import generate_from_tests from eth2spec.phase0 import spec as spec from importlib import reload from eth...
python
#!/usr/bin/env python import os import sys import shutil download_fail_times = 0 pvmp3_path = sys.path[0] download_path = os.path.join(pvmp3_path, "source") final_src_path = os.path.join(pvmp3_path, "src") print('download pvmp3 source file') if not os.path.exists(final_src_path): while True: if not os.p...
python
import csv from environs import Env env = Env() env.read_env() fieldnames = ['id', 'nome_da_receita', 'descricao_da_receita'] def listar_receitas(): with open(env('RECEITAS_CSV')) as f: reader = csv.DictReader(f) return [receita for receita in reader] def buscar_receitas(nome): with open(...
python
from datetime import datetime, timedelta from pynput.keyboard import Listener as KeyboardListener from pynput.mouse import Listener as MouseListener from apis.mongo.mongo_client import log_event, log_processes from apis.monitoring_details.win32_window_details import active_window_process, all_open_windows # logging....
python
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # noc.core.snmp.ber tests # ---------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # ------------------------------------------------------...
python
import logging from itertools import cycle, islice from typing import Callable, List, Optional import torch from hypergraph_nets.hypergraphs import ( EDGES, GLOBALS, N_EDGE, N_NODE, NODES, RECEIVERS, SENDERS, ZERO_PADDING, HypergraphsTuple, ) from strips_hgn.hypergraph.hypergraph_v...
python