content
stringlengths
5
1.05M
# coding: utf-8 from io import StringIO config_spec = StringIO( f""" [general] language = string(default="default") announce_ui_messages = boolean(default=True) show_file_name_as_title = boolean(default=False) open_with_last_position = boolean(default=True) auto_check_for_updates = boolean(de...
# encoding=utf-8 import networkx as nx import matplotlib.pyplot as plt from networkx.algorithms import approximation as apxa print nx G = nx.Graph() # 建立一个空的无向图 G.add_node(6) # 添加一个节点1 G.add_edges_from([(1,2),(1,3)]) G.add_edge(2,3) # 添加一条边2-3(隐含着添加了两个节点2、3) G.add_weighted_edges_from([(1,6,14.0),(1,3,9....
#!/usr/bin/env python # coding : utf8 import numpy as np import matplotlib.pyplot as plt def ff(inp): return np.log10(inp) def fb(K, ph): r = ph / 180.0 * np.pi gs = K * np.exp(-1.0j * r) ms = gs / (1 + gs) z = ff(np.abs(ms)) r = z if z > 40: r = 0 a = 180 * np.pi / np.ang...
''' Created on Mar 12, 2014 Copyright 2014-2015 Luigi De Russis 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 django.shortcuts import render from rest_framework.generics import ( ListAPIView, RetrieveAPIView, ) from rest_framework.views import APIView from rest_framework.response import Response from django.core import serializers from django.http import Http404 from rest_framework.permissions import AllowAny fro...
import pygame, pgeng from pygame.locals import * pygame.init() clock = pygame.time.Clock() screen = pgeng.Screen((320, 240)) display = screen.get_display() small_font = pgeng.create_font((255, 255, 255))[0] original_points = [(150, 180), (170, 180), (160, 200)] original_center = [160, 180] poly = pgeng...
import os import cPickle import glob import numpy as np #np.random.seed(1337) from keras.models import Sequential, Graph from keras.layers import Embedding, LSTM, Dense, Merge, MaxPooling1D, TimeDistributed, Flatten, Masking, Input, Dropout, Permute from keras.regularizers import l2, activity_l2 from code.learning.wo...
from tkinter import * import os import webbrowser app = Tk() app.title("MyPhone") logo=PhotoImage(file='logo.png') app.iconphoto(False,logo) app.minsize(1179,773) app.maxsize(1179,773) bg = PhotoImage(file = "bg2.png") canvas1 = Canvas( app, width = 1179,height = 773) canvas1.pack(fill = 'both', expand = True) canva...
from enum import Enum from typing_extensions import Final class GCODE(str, Enum): HOME = "G28.2" MOVE = "G0" DWELL = "G4" CURRENT_POSITION = "M114.2" LIMIT_SWITCH_STATUS = "M119" PROBE = "G38.2" ABSOLUTE_COORDS = "G90" RELATIVE_COORDS = "G91" RESET_FROM_ERROR = "M999" PUSH_SPE...
position = [0, 0] position_2 = [0, 0] waypoint = [10, 1] facing = 1 directions = ((0, 1), (1, 0), (0, -1), (-1, 0)) moves = { 'N': 0, 'E': 1, 'S': 2, 'W': 3, } rotations = { 'R': 1, 'L': -1, } waypoint_rotations = [ lambda x: [x[0], x[1]], lambda x: [x[1], -x[0]], lambda x: [-x[0]...
#! /usr/bin/env python # Copyright 2021 Intel Corporation # # 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...
from discord.ext import commands import discord from .helpers import guild from common import common def normalize(cog): return 'cogs.'+cog+'_setup' class Core(commands.Cog): def __init__(self, bot): self.bot = bot self.masterLogger = common.getMasterLog() @commands.group(pass_context=T...
from flask import Blueprint, request, render_template from app.models import Category, Product import json bp_front_end = Blueprint('api_front_end', __name__, url_prefix='/') @bp_front_end.route('', methods=['GET']) def home(): return render_template("home.html.jinja") @bp_front_end.route('category_list', met...
from re import Scanner from .lexerconstants import CHAR_MAP, NUM_CONST, NUM_SIGN_CONST from .debug import Debug as dbg class Tokeniser(object): def __init__(self, type=None, value=None, debug=False): self.value = value self.type = type self.debug = debug def __str__(self): ret...
import pytest from django.urls import reverse @pytest.mark.django_db def test_slug_redirect(django_app, volunteer, event): response = django_app.get( reverse("core:event_detail", kwargs=dict(pk=event.pk, slug="nottheactualslug")), user=volunteer, ) assert response.location # is a redirect...
# Copyright (c) 2019 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 app...
import torch import inspect from typing import Callable, Union from pytorch_lightning import Trainer as PLTrainer from pytorch_lightning import LightningModule from pytorch_lightning import LightningDataModule from pytorch_lightning.loggers import TensorBoardLogger from .metrics import MetricBase from .tasks import Gen...
#!/usr/bin/env python # -*- coding: utf8 -*- # My imports from __future__ import division, print_function import numpy as np import argparse def ll_filter(fname, col, limit, sign, element): data = np.loadtxt(fname, skiprows=1, unpack=True) if sign and element: i = (data[col] > limit) | (data[1] == el...
# -*- coding: utf-8 -*- # Copyright (c) 2022 Theo Hussey # License: Apache 2.0 # Project: KiAuto (formerly kicad-automation-scripts) """ Tests for 'pcbnew_do export_gencad' For debug information use: pytest-3 --log-cli-level debug """ import os import sys import re # Look for the 'utils' module from where the script ...
import torch def shift_left(matrix, dimension): """Shift tensor left by one along specified dimension. This operation performed in-place""" m_len = matrix.size()[dimension] matrix.narrow(dim=dimension, start=0, length=m_len - 1) \ .copy_(matrix.narrow(dim=dimension, start=1, length=m_len - 1)) d...
import os import cv2 import numpy as np import pickle import math from shutil import copyfile from tqdm import trange, tqdm from PIL import Image import argparse def obtain_ann_dict(img_root, ann_root): ann_dict = {} assert (os.path.isdir(img_root)), 'Path does not exist: {}'.format(img_root) assert (os.p...
class Puzzle: """" Snapshot of a full-information puzzle, which may be solved, unsolved, or even unsolvable. """ def fail_fast(self): """ Return True iff Puzzle self can never be extended to a solution. Override this in a subclass where you can determine early that ...
# -*- coding: utf-8 -*- import torch.nn as nn import torch.nn.functional as F import torch class CPM(nn.Module): def __init__(self, k): super().__init__() self.k = k """ Todo: Compute all parameters""" self.pool_center = nn.AvgPool2d(kernel_size=9, stride=8, padding=1) """------Stage 1------""" # Pa...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/1/16 9:30 AM # @Author : Insomnia # @Desc : 定义一个队列并实现函数max得到队列里的最大值。要求max,pushBack,popFront的时间复杂度都是o(1)。 # @File : MaxNumInQue.py # @Software: PyCharm # 思路用单调队列 class MonitonicQue: def __init__(self): self.data = [] def push(self,...
from ast import While from operator import truediv import operator import time import os import sys import subprocess import math from turtle import clear MacOS = "1" Windows= "2" Errorbol = False def clear_console(): if os.name == 'nt': os.system('cls') else: os.system('clear') clear_console(...
import torch import torch.nn as nn import torch.nn.functional as F import dgl import numpy as np """ Graph Transformer """ from layers.graph_transformer_layer import GraphTransformerLayer from layers.mlp_readout_layer import MLPReadout class SAN(nn.Module): def __init__(self, net_params): super...
import dateutil.parser import pytz from .trace import ( ArbitrarySerializer, ArbitraryStartSerializer, ArbitraryEndSerializer, ) from eemeter.structures import ( EnergyTrace, ModelingPeriod, ModelingPeriodSet ) def deserialize_meter_input(meter_input): # verify type type_ = meter_inp...
import asyncio import contextlib import logging from contextlib import asynccontextmanager, suppress from enum import Enum from typing import Any, AsyncIterator, Awaitable, Dict, Optional, cast import distributed from dask_task_models_library.container_tasks.events import ( BaseTaskEvent, TaskCancelEvent, ...
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QApplication, QMessageBox, QListWidget import Utility import search_API import project_init class Ui_Form(object): dictionary = {} doc_lens = {} bm25_dictionary = {} def __init__(self): self.dictionary, ...
from .process import archive
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
def linear_search(arr, n, x): for i in range(0, n): if (arr[i] == x): return i return -1 ## Testing arr = [2, 4, 6, 8, 3, 6, 9] result = linear_search(arr, len(arr), 3) if(result == -1): print("Element is not present in array") else: print(f"Element is present at index: {result}")
import os # Public ip and default port c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.port = 8888 # Allow to be run as root in docker c.NotebookApp.allow_root = True c.NotebookApp.open_browser = False #c.NotebookApp.notebook_dir = os.getenv("NOTEBOOK_DIR","") c.NotebookApp.notebook_dir = "/home/work/project" # No pass...
class Type: def __init__(self): self.error_msg = "is not valid" def __comply__(self, value, arg_name): raise NotImplementedError("This function must be implemented in children class") def __check__(self, value, arg_name): if not self.__comply__(value, arg_name): raise V...
import codecs from codecs_to_hex import to_hex BOM_TYPES = [ 'BOM', 'BOM_BE', 'BOM_LE', 'BOM_UTF8', 'BOM_UTF16', 'BOM_UTF16_BE', 'BOM_UTF16_LE', 'BOM_UTF32', 'BOM_UTF32_BE', 'BOM_UTF32_LE', ] for name in BOM_TYPES: print('{:12} : {}'.format( name, to_hex(getattr(codecs, name), 2)))
from CTFd.plugins import register_plugin_assets_directory from CTFd.plugins.flags import get_flag_class from CTFd.models import db, Solves, Fails, Flags, Challenges, ChallengeFiles, Tags, Hints from CTFd.utils.user import get_ip from CTFd.utils.uploads import delete_file from flask import Blueprint class BaseChalleng...
import discord from discord.ext import commands from core.bot import is_owner from core.logger import logger from data.colors import colors class FullAccess(commands.Cog): """Выдать полный доступ""" def __init__(self, bot): self.bot = bot @commands.command(aliases = [ ...
#%% import os import sys try: os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/') sys.path.append('/Volumes/GoogleDrive/My Drive/python_code/maggot_models/') sys.path.append('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/') except: pass from pymaid_creds import url, nam...
import csv, re, spacy, textacy from spacy.symbols import * nlp = spacy.load('en_core_web_sm') # trim unneccessary leading phrases def trim_leading(text): return re.sub('^(Group )?portrait(,| of) ', '', text, flags=re.I) # trim unneccessary trailing phrases def trim_trailing(text): return re.sub(', another (v...
import json import xbmc import xbmcvfs from . import utils as utils from xml.dom import minidom from xml.parsers.expat import ExpatError class GuiSettingsManager: doc = None def __init__(self): # first make a copy of the file xbmcvfs.copy(xbmc.translatePath('special://home/userdata/guisetting...
# Copyright 2016 Open Source Robotics Foundation, 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 applicable law...
""" Thread to play audio. Constantly plays silence when not in use to maintain stim calibration """ from pyaudio import PyAudio, paContinue from time import sleep import numpy as np class AudioThread: def __init__(self): self.bitrate = 48000 self.audiobuf = b"" self.p = PyAudio() ...
""" util.py Utilities and helper functions that don't require mido """ import sys import itertools import collections import collections.abc # SysEx Manufacturer ID YAMAHA = 0x43 # Formatting onehex = "{:1X}".format twohex = "{:02X}".format def hexspace(seq): """ Returns a string representation as two dig...
# Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo: – IMC abaixo de 18,5: Abaixo do Peso – Entre 18,5 e 25: Peso Ideal – 25 até 30: Sobrepeso – 30 até 40: Obesidade – Acima de 40: Obesidade Mórbida print(f'='*...
# -*- coding: utf-8 -*- """ Created on Tue Nov 17 11:17:06 2020 @author: Mahamed """ ''' Support vector machine with classification parameter set by cross validation ''' from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC tuned_params = [ {'kernel':['rbf'], 'gamma':[1e-1...
# Generated by Django 2.2.7 on 2020-01-31 08:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user', '0002_auto_20200128_1742'), ] operations = [ migrations.RemoveField( model_name='profile', name='avatar', ), ...
""" Tests for scraping and processing """ import pytest import recipe_recommender as rr @pytest.fixture() def testing_data(): data = rr.scraping_and_processing.bodybuilding.scrape_db(test=True) return data def test_bodybuilding_scrape(testing_data): """ Test that pulling single recipe from bodybuildi...
import os import shlex import sys import pytest from sanic_envconfig import EnvConfig @pytest.fixture() def config(request): class C(EnvConfig): ATTRIBUTE_STR: str = 'default_str' ATTRIBUTE_INT: int = 1 ATTRIBUTE_FLOAT: float = 1.5 ATTRIBUTE_BOOL: bool = True return C @pyt...
from .gener_log import * from .gener_powerlaw_fits import * from .gener_pdf_for_data_run import *
import unittest from porthole.app import default_session from porthole.models import AutomatedReport, AutomatedReportContact, AutomatedReportRecipient from porthole.models import ReportLog, ReportLogDetail class TestReportModels(unittest.TestCase): def test_create_report_and_recipients(self): report = Aut...
#!/bin/env python # Home to work # https://maps.googleapis.com/maps/api/directions/json?origin=901+Clearview+Dr+Bedford+Tx&destination=111+Customer+Way+Irving+Tx&avoid=tolls&key=AIzaSyDg5cmsPRKv2BqH889-y1AS8Y2r-de9McU # Home to parents # https://maps.googleapis.com/maps/api/directions/json?origin=901+Clearview+Dr+Bed...
""" Copyright 2015 Austin Ankney, Ming Fang, Wenjun Wang and Yao Zhou Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law o...
""" **MeanFunction Module** The MeanFunction module contains classes used for constructing mean functions for GP emulators. A base ``MeanBase`` class is provided, which implements basic operations to combine fixed functions and fitting parameters. The basic operations ``f1 + f2``, ``f1*f2``, ``f1**f2`` and ``f1(f2)`` ...
from pdfmix.core import create_mixture_pdf_files_from_cif_directory import math create_mixture_pdf_files_from_cif_directory( "../notebooks/data", "../notebooks/cifs", output_pattern="{:08d}.nc", fracs=[ [0.0, 1.0], [1.0, 0.0], [0.05, 0.95], [0.95, 0.05], [0.2, 0...
import os from flask import Flask from flask import Response from flask import request from flask import render_template from twilio import twiml from twilio.rest import TwilioRestClient from twilio.util import TwilioCapability from twilio.access_token import AccessToken # Required to connect to Twilio TWILIO_ACCOUNT...
from django.http import HttpResponse, JsonResponse from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest.maingame.models import Hotspot, Player, Group from rest_framework.views import APIView from rest_framework.response import Response import uuid from rest.alias imp...
import pandas as pd import numpy as np import requests def _set_reference_time(time0, time1): return time0 + '/' + time1 class FrostDataRetriever: def __init__(self, longitude=10, latitude=59, initial_time_stamp='2020-07-20T00:00:00', final_time_stamp='2020-07-31T23:59:59'): self.c...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import sys from pyblake2 import blake2b def contract_hash( from_addr_base16: str, nonce: int, function_counter: int) -> bytes: """ Should match what the EE does: blake2b256( [0;32] ++ [0;8] ++ [0;4] ) pk ++ nonce ++ function_counter """ def hash(data: bytes) -> bytes: ...
from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() if rank == 0: data = [(x+1)**x for x in range(size)] print 'we will be scattering:',data else: data = None data = comm.scatter(data, root=0) data += 1 print 'rank',rank,'has data:',data newData = comm.gather(data,...
# ---Stdlib--- from os import listdir from os.path import join # ---Dependencies--- import torch import torch.nn.functional as F import numpy as np from sklearn.decomposition import PCA def get_device(device=None): if isinstance(device, torch.device): return device return torch.device(device) if dev...
#! /usr/bin/env python3 import argparse import os import re from sys import modules # TODO: wrap the "name","after","counter" into a class class PerfMMU(object): def __init__(self, name, counters, func): self.name = name self.counter = counters self.func = func ptw_counter = dict() filter...
import turtle wn = turtle.Screen() jhonny = turtle.Turtle() jhonny.speed(2) jhonny.penup() jhonny.setposition(-250,75) jhonny.pendown() jhonny.pensize(10) jhonny.forward(80) jhonny.backward(40) jhonny.right(90) jhonny.forward(120) jhonny.penup() jhonny.setposition(-130, 75) jhonny.pendown() jhonny.left(23.5) jhonn...
""" Start with a tree file, use ete3 to create a pairwise distance for all nodes. Basically this is the distance matrix but as tuples. if we have a tree like ----A _____________|y | | | ----B ________|z | ...
#!/usr/bin/env python # coding=utf-8 from setuptools import setup setup( name = 'pogopowerupcost', packages = ['pogopowerupcost'], version = '1.0.2', download_url = 'https://github.com/mathiasbynens/pogopowerupcost/tarball/v1.0.2', description = 'Easily calculate how much stardust and candy it takes to power-up ...
import quandl csv_name = input('What should the csv be called? ') data = quandl.get("LBMA/GOLD", authtoken="Pa5fcY5AMKGfoipiGqjs", start_date="2017-02-25") data = data.iloc[::-1] data.to_csv('quandl_gold_data_{}.csv'.format(csv_name), mode = 'w+') #End
import secrets from datetime import datetime for i in range(61): timestamp = str(datetime.timestamp(datetime.now())) key_id = secrets.token_urlsafe(16) randbytes = secrets.token_bytes(128) with open("key-{0}".format(key_id), "wb") as data: data.write(timestamp.encode() + b"\n") data.wr...
from bs4 import BeautifulSoup import requests import pandas as pd import os # Setting up session s = requests.session() # List contaiting all the films for which data has to be scraped from IMDB films = [] # Lists contaiting web scraped data names = [] ratings = [] genres = [] # Define path where your films are p...
# -*- coding: utf-8 -*- from sanic.response import HTTPResponse from rafter.app import Rafter from rafter.http import Response from rafter.filters import filter_transform_response def fake_request(): app = Rafter() request = app.request_class(b'/', {}, '1.1', 'GET', None) request.app = app request.b...
import os import sys import pathlib from scipy import ndimage, misc from torch._C import ErrorReport dir_path = os.path.dirname(pathlib.Path(__file__).resolve().parent) # dir_path = os.path.dirname(os.path.realpath(__file__).parent) sys.path.insert(1, dir_path) import matplotlib.pyplot as plt from torch.utils.data ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 3 21:43:46 2022 @author: stephane """ import numpy as np import pandas as pd hbar = 6.625E-34/(2*np.pi) m0 = 9.109E-31 eps0 = 8.85E-14 q = 1.602E-19 # define layer stack class class stack: # The init method def __init__(self, wl): ...
"""A build-system abstraction for CMake. One instance is one build configuration, known at construction. I've never had a use case where I was interested in building multiple configurations simultaneously. Either I'm testing or debugging or I'm benchmarking or publishing. Using this lowest common denominator lets us s...
from pytest_mypy_plugins.collect import File from pytest_mypy_plugins.item import YamlTestItem def django_plugin_hook(test_item: YamlTestItem) -> None: custom_settings = test_item.parsed_test_data.get('custom_settings', '') installed_apps = test_item.parsed_test_data.get('installed_apps', None) if instal...
import sys import os import re import numpy as np from galry import log_info, log_debug import re """Font atlas tools for loading files generated by AngelCode Bitmap Font Generator 1.13. The link is: http://www.angelcode.com/products/bmfont/ """ __all__ = ["load_png", "load_fnt", "get_text_map", "load_font"] def ...
""" Test cases for stix2patterns/helpers.py. """ from stix2patterns.helpers import leading_characters def test_leading_characters(): assert leading_characters('[file:size = 1280]', 2) == '[f' assert leading_characters(' [file:size = 1280]', 2) == '[f' assert leading_characters('( [file:size = 1280])', 2...
"""Dataset Tests (core methods)""" import copy import json import re import tempfile from os import remove from os.path import join import pytest from hdx.utilities.dictandlist import merge_two_dictionaries from hdx.utilities.loader import load_yaml from hdx.api import __version__ from hdx.api.configuration import Co...
class SkillArmor: def __init__(self, dbRow): self.id = dbRow[0] self.skillMaxLevel = dbRow[1] self.armorID = dbRow[2] self.armorName = dbRow[3] self.armorRarity = dbRow[4] self.armorType = dbRow[5] self.skillLevel = dbRow[6] def __repr__(self): return f"{self.__dict__!r}"
#!/usr/bin/env python3 # 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. from parlai.core.worlds import World from parlai.chat_service.services.messenger.worlds import OnboardWorld # --------...
#!/usr/bin/env python from sseclient import SSEClient from Queue import Queue import requests import json import threading import socket import sys import time from text import Text from pprint import pprint from led.eyes import EyeChanger BASE_DB = 'https://robotman.firebaseIO.com/' DB = BASE_DB + 'control/' URL = D...
import sys import json import time import uuid import redis def AD(): ret = {} ret['adId'] = 0 ret['campaignId'] = 0 ret['keyWords'] = [] ret['relevanceScore'] = 0 ret['pClick'] = 0 ret['bidPrice'] = 0 ret['rankScore'] = 0 ret['qualityScore'] = 0 ret['costPerClick'] = 0 ret...
# this cmd print itself, # but this trick read file,it's not a QUINE print open(__file__).read()
import time import numpy as np default_header = { 'User-Agent': 'SOME_UA_STRING', } asian_proxies = { 'http': 'SOME_PROXY', 'https': 'SOME_PROXY' } global_proxies = { 'http': 'SOME_PROXY', 'https': 'SOME_PROXY' } def random_delay(min=15, max=17): delay = np.random.rand() * (max-min) + min ...
from broker.broker import Broker __all__ = ["Broker"]
import itertools with open("day_25/input.txt") as file: board = [list(line.strip()) for line in file.readlines()] SIZE_X = len(board[0]) SIZE_Y = len(board) STEP_COUNTER = itertools.count(1) has_changed = True while has_changed: has_changed = False step = next(STEP_COUNTER) for direction, size in z...
# Created by Giuseppe Paolo # Date: 27/08/2020 from gym.envs.registration import register register( id='CollectBall-v0', entry_point='gym_collectball.envs:CollectBall' )
import tensorflow as tf import hyperchamber as hc def repeating_block(component, net, depth, filter=3): ops = component.ops config = component.config layer_regularizer = config.layer_regularizer filter_size_w = filter filter_size_h = filter filter = [1,filter_size_w,filter_size_h,1] stride ...
#By Ashok Kumar Chaudhary """ This Code loads data and extract features from them and label them.""" import myfeat import pandas as pd import numpy as np from numpy import matrix import xlwt from scipy.stats import kurtosis, skew import matplotlib.pyplot as plt book = xlwt.Workbook(encoding="utf-8") sheet1 = book...
from qfunction.base.base import * from numpy import sin, cos import numpy as np from math import atan def q_sin(u,q,cpx=False,israd=True): u = radian(u) if( not israd) else u b = 1j u=u*1j if cpx: return ((q_exp(u,q)-q_exp(-u,q)))/(2*b) else: return (((q_exp(u,q)-q_exp(-u,q)))/(2*b)...
# Sayangku Virtual Asisstant Projects import speech_recognition as sr import pyttsx3 import wikipedia import os import datetime import sys import brainlypy from translate import Translator recognizer = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1...
import json import logging from typing import Tuple import joblib import numpy as np import pandas as pd import typer from scipy.stats import randint from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import RandomizedSearchCV, train_test_split cli = typer.Typer() def optimized_train(X...
from __future__ import absolute_import import logging from django.conf import settings from novaclient import client as nova_client from horizon.utils import functions as utils from horizon.utils.memoized import memoized # noqa from horizon.utils.memoized import memoized_with_request # noqa from openstack_dashbo...
from __future__ import absolute_import, print_function import torch import torch.nn as nn import torch.nn.functional as F from code.models.backbone.ResNet_Dilated import _ConvBnReLU class _ImagePool(nn.Module): def __init__(self, in_ch, out_ch): super().__init__() self.pool = nn.AdaptiveAvgPool2d(...
""" An Armstrong number is an n-digit number that is equal to the sum of the n'th powers of its digits. Determine if the input numbers are Armstrong numbers. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Each line in this file has a positive integer. E.g. 6 153 351 OUTPUT SAMP...
# Generated by Django 2.2.5 on 2019-09-20 21:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('mesfactory', '0007_auto_20190917_2236'), ] operations = [ migrations.AlterModelOptions( name='f...
from django import forms from announcement.models import Announcement class AnnouncementForm(forms.ModelForm): class Meta(): model = Announcement fields = ('author', 'title', 'text', 'picture')
# A Naive recursive Python program to fin minimum number # operations to convert str1 to str2 def edit_distance(str1,str2, m, n): # If the first string is empty. the only option # is to insert all characters of second string # into the first if m == 0: return n # Similarly, it goes the op...
import os from math import factorial from itertools import permutations def borrarPantalla(): #Definimos la función estableciendo el nombre que queramos if os.name == "posix": os.system ("clear") elif os.name == "ce" or os.name == "nt" or os.name == "dos": os.system ("cls") def getFileName()...
from networkx import DiGraph from .cvrp_solver import CVRPSolver, Truck, CVRPDefinition from .util import closest_neighbor class GreedyCVRPSolver(CVRPSolver): def get_info(self) -> str: return 'Greedy' def solve_cvrp(self, problem: CVRPDefinition) -> DiGraph: depot = 'Depot' solution = DiGraph() solution...
""" Defaults module for AWS cleanup """ AWS_REGION = 'us-east-2' CLUSTER_PREFIXES_TO_EXCLUDE_FROM_DELETION = {'jnk': '36'} MINIMUM_CLUSTER_RUNNING_TIME_FOR_DELETION = 10 AWS_CLOUDFORMATION_TAG = 'aws:cloudformation:stack-id' CONFIRMATION_ANSWER = 'yes-i-am-sure-i-want-to-proceed'
from django.core.urlresolvers import reverse from django.db import models from django.contrib.auth.models import User class Staff(models.Model): user = models.OneToOneField(User) about = models.TextField(max_length=1024) def __str__(self): return self.user.get_full_name() def get_url(self): ...