content
stringlengths
5
1.05M
from matplotlib import pyplot as plt from matplotlib import cm from matplotlib import animation from optimisation import FireflyOptimizer import numpy as np from optimisation import Ackley f_alg = FireflyOptimizer(population_size=10, problem_dim=2, generations=100) func = Ackley(2) N = 100 x = np.linspace(-5, 5, N) ...
import socket import pickle import pandas as pd import matplotlib.pyplot as plt def graph_setting(): plt.ion() fig, ax = plt.subplots() return ax def data_get(df, conn, i): data = conn.recv(1024) data = float(pickle.loads(data)) df_temp = pd.DataFrame([[data]], columns=['data'...
import re from csv import DictReader, DictWriter from .utils import get_headers class Dataset(object): def __init__(self, key=None, headers=None, data=None): self.headers = headers self.data = data self.key = key def write(self, fd, delim='\t'): writer = DictWriter(fd, self.he...
from telnetlib import Telnet from uuid import uuid4 from time import sleep from hashlib import md5 from os import chmod from re import compile as compile_regex from sys import version_info from .abstractremoteshell import AbstractRemoteShell from .shellresult import ShellResult from .streamreader import PrefixedStream...
""" 二分探索 <最悪実行時間に関する漸化式> T(n) = | Θ(1) if n = 1 | T(n/2) + c if n > 1 ループの度に検査範囲が半減するので、Θ(lgn)となる。 """ def binary_search(A, v): left = 0 right = len(A) - 1 while left <= right: i = (left + right) // 2 if v < A[i]: right = i - 1 ...
# # RawIO # Copyright (c) 2021 Yusuf Olokoba. # from cv2 import findTransformECC, MOTION_TRANSLATION, TERM_CRITERIA_COUNT, TERM_CRITERIA_EPS from numpy import asarray, eye, float32 from PIL import Image from sklearn.feature_extraction.image import extract_patches_2d from typing import Callable def markov_similar...
import numpy as np from glob import glob import os from sklearn.model_selection import train_test_split base_path = "/media/ml/data_ml/EEG/deepsleepnet/data_npy" files = glob(os.path.join(base_path, "*.npz")) train_val, test = train_test_split(files, test_size=0.15, random_state=1337) train, val = train_test_split(t...
from ..game import Actor def test_id(): actor1 = Actor() actor2 = Actor() assert actor1.id assert actor2.id assert actor1.id != actor2.id def test_add_food(): actor = Actor() assert actor.food == 0 actor.add_food(10) assert actor.food == 10 actor.add_food(5) assert act...
import deepmerge import functools import importlib import logging import yaml from inspect import getmembers, isfunction from urllib import parse, request from wcmatch import fnmatch from . import macros, middleware log = logging.getLogger("netbox_rbac") # Collect all public functions from macros. functions = [ ...
from django.core.paginator import Paginator from django.shortcuts import redirect, render, get_object_or_404 from comps.models.comp import Comp from comps.models.heat import Heat from comps.models.heatlist_error import Heatlist_Error def delete_heatlist_error(request, error_id): heatlist_error = get_object_or_404...
# Generated by Django 3.0.6 on 2020-06-12 16:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('My_Account', '0017_auto_20200612_1522'), ] operations = [ migrations.RenameField( model_name='sharing_image', old_name='Like...
import pygame from pygame.locals import * from GUI.Colours import Colours from GUI.Measures import Measures from GUI.Point import Point from GUI.BarPoint import BarPoint from GUI.BearoffPoint import BearoffPoint from GUI.Checker import Checker class GUIBoard: def __init__(self): pass de...
from cloud_scanner_azure.config.azure_credential_config import ( AzureCredentialConfig) class AzureResourceServiceConfig: """Configuration required for usage of AzureResourceService.""" def __init__(self, subscription_id, creds: AzureCredentialConfig): self.credentials = creds self.subscr...
# -*- coding: utf-8 -*- # Imports import sys,re,os import glob import numpy as n # Script information __author__ = "Sergi Rodà Llordés" __version__ ="1.0" __maintainer__="Sergi Rodà Llordés" __email__="sergi.rodallordes@bsc.es" class pKa: def __init__(self,PDB,Ser_residue): self.__PDB = PDB sel...
from rest_framework import serializers from products.models import Product, Category class CategorySerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Category fields = ("id", "name") class ProductSerializer(serializers.ModelSerializer): class M...
import datetime import json import discord from discord.ext import commands import requests ''' スプラトゥーン2絡みのコマンド ''' class Splatoon2(commands.Cog, name='スプラトゥーン2'): def __init__(self, bot): self.bot = bot @commands.command(name='バイトシフト') async def say_salmon_schedule(self, ctx):...
from django.db import models # Create your models here. from django_countries.fields import CountryField from django.contrib.gis.db import models from django.db.models import Manager as GeoManager class Site(models.Model): id = models.AutoField(primary_key=True) site = models.CharField('Site name', max_lengt...
#!/usr/bin/env python # Pull out yearly precipitation # Daryl Herzmann 26 Jul 2004 import pg, dbflib, mx.DateTime, shutil, shapelib from pyIEM import wellknowntext mydb = pg.connect('wepp','iemdb') sts = mx.DateTime.DateTime(2005,3,1) ets = mx.DateTime.DateTime(2005,11,1) interval = mx.DateTime.RelativeDateTime(days=...
#!/usr/bin/env python # # Simple websocket server to perform signaling. # import asyncio import binascii import os import websockets clients = {} async def echo(websocket, path): client_id = binascii.hexlify(os.urandom(8)) clients[client_id] = websocket try: async for message in websocket: ...
import sys import traceback import logging from glass import http from . import highlight ERROR_TEMPLATE = ''' <title>{code} {title}</title> <h1>{title}</h1> <p>{description}</p> ''' logger = logging.getLogger('glass.app') class HTTPError(Exception): code = 500 description = "Internal Server Error" def ...
""" An evolving population of genotypes(Ideally for optimizing network hyperparameters). See genotype constraint docs in spikey/meta/series. Examples -------- .. code-block:: python metagame = EvolveNetwork(GenericLoop(network, game, **params), **metagame_config,) population = Population(metagame, **pop_conf...
#!/usr/bin/env python from setuptools import setup, find_packages packages = ['eda.' + p for p in find_packages('eda', exclude=['test', 'test*', '*.t'])] packages.append('eda') #packages=['eda', 'eda.components', 'eda.components.ST', 'eda.circuits'], setup( name='EDA', version='1.0.1', author='Pawe...
import gym import retro import os import numpy as np from PIL import Image from gym import spaces from collections import deque import cv2 SCRIPT_DIR = os.getcwd() #os.path.dirname(os.path.abspath(__file__)) # Taken from: https://gitlab.cs.duke.edu/mark-nemecek/vel/-/blob/cfa17ddd8c328331076b3992449665ccd2471bd3/vel...
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap fig, axes = plt.subplots(2, 1) axes[0].set_title("Hammer projection") map = Basemap(projection='hammer', lon_0 = 10, lat_0 = 50, ax=axes[0]) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral',lake_color='aqua') map.drawcoas...
""" Forward-ports of types from Python 2 for use with Python 3: - ``basestring``: equivalent to ``(str, bytes)`` in ``isinstance`` checks - ``dict``: with list-producing .keys() etc. methods - ``str``: bytes-like, but iterating over them doesn't product integers - ``long``: alias of Py3 int with ``L`` suffix in the ``...
from pycocotools.coco import COCO import matplotlib.pyplot as plt import cv2 import os import numpy as np import random import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader,Dataset from skimage import io,transform import matplotlib.pyplot as plt import os import torch from ...
import LAMMPyS as lp steps = lp.Steps('test.dump') step = steps[-1] atoms = step.atoms
def do_training(train, train_labels, test, test_labels, num_classes): #set TensorFlow logging level to INFO tf.logging.set_verbosity(tf.logging.INFO) # Build 2 hidden layer DNN with 10, 10 units respectively. classifier = tf.estimator.DNNClassifier( # Compute feature_columns from dataframe keys...
from __future__ import absolute_import import abc class Writer(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def text(self, text): pass @abc.abstractmethod def start(self, name, attributes=None): pass @abc.abstractmethod def end(self, name): p...
import utime import machine from machine import Timer, Pin, RTC import time import ntptime import micropython import config import control import mqtt_reporting def set_ntp_time(timer): ntptime.host = "tempus1.gum.gov.pl" for i in range(1,10): try: t = ntptime.time() tm = utime....
import pytest from pathlib import Path from yalul.lex.scanners.grouping import GroupingScanner from yalul.lex.token_type import TokenType @pytest.fixture(scope='function') def open_file(request): return open(str(Path.cwd()) + "/tests/lex_examples/" + request.param) class TestShouldLex: def test_when_is_left...
{"filter":false,"title":"bot.py","tooltip":"/bot.py","undoManager":{"mark":53,"position":53,"stack":[[{"start":{"row":163,"column":18},"end":{"row":163,"column":35},"action":"remove","lines":["BOT_USERNAME_HERE"],"id":2},{"start":{"row":163,"column":18},"end":{"row":163,"column":19},"action":"insert","lines":["k"]}],[{...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
class Solution: def minDeletionSize(self, A: List[str]) -> int: return sum(list(column) != sorted(column) for column in zip(*A))
import sys import os import os.path import re import shutil from setuptools import setup from setuptools.command.install_lib import install_lib from setuptools.command.install import install import setuptools.command.bdist_egg import distutils.spawn import subprocess import sys import glob exclude_directories = lambda...
from dataclasses import dataclass from bindings.csw.graph_style_type import GraphStyleType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class GraphStyle1(GraphStyleType): """The style descriptor for a graph consisting of a number of features. Describes graph-specific style attributes. """ ...
##################################################### ## librealsense streams test ## ##################################################### # This assumes .so file is found on the same directory import pyrealsense2 as rs # Prettier prints for reverse-engineering from pprint import pprint # Get r...
# ██████ ██▓ ▄▄▄ ██▒ █▓ ██▓ ▄████▄ ██▓███ ██▓▒██ ██▒▓█████ ██▓ # ▒██ ▒ ▓██▒ ▒████▄ ▓██░ █▒▓██▒▒██▀ ▀█ ▓██░ ██▒▓██▒▒▒ █ █ ▒░▓█ ▀ ▓██▒ # ░ ▓██▄ ▒██░ ▒██ ▀█▄▓██ █▒░▒██▒▒▓█ ▄ ▓██░ ██▓▒▒██▒░░ █ ░▒███ ▒██░ # ▒ ██▒▒██░ ░██▄▄▄▄██▒██ █░░░██░▒▓▓▄ ▄██▒ ▒██▄█▓...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/worker_service.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.prot...
def validate_cell(cell: tuple) -> tuple: x, y = cell if x == 6: x = 0 elif x == -1: x = 5 if y == 6: y = 0 elif y == -1: y = 5 return x, y def get_cell(cell: tuple, field: list) -> str: row, col = cell return field[row][col] def set_cell(cell: tuple, f...
# nukedatastore tests import pytest import datetime from nukedatastore import NukeDataStore, NukeDataStoreError def test_datastore_crud(datastore): datastore['project_data'] = {'id': 1234, 'name': 'project name'} assert len(datastore.list()) == 1 assert datastore.list()[0] == 'project_data' assert da...
# Copyright (c) 2020 Graphcore Ltd. # Copyright 2018 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 appl...
import torch import warprnnt_pytorch as warp_rnnt from torch.autograd import Function from torch.nn import Module from .warp_rnnt import * __all__ = ['rnnt_loss', 'RNNTLoss'] class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, reduction): """ acts:...
from utils import color from browser import help import random def get(cmds, typ, add_attr=None): ''' USE: error.get(cmds, type, [optional:add_attr]) where add_attr must be < 3 Description: Returns a correctly colored message according to declared "typ" ''' #---------------------------------------------------...
from brownie import accounts, PassiveStrategy from brownie.network.gas.strategies import ExponentialScalingStrategy import os STRATEGIES = [ # "0x40C36799490042b31Efc4D3A7F8BDe5D3cB03526", # V0 ETH/USDT # "0xA6803E6164EE978d8C511AfB23BA49AE0ae0C1C3", # old V1 ETH/USDC # "0x5503bB32a0E37A1F0B8F8F...
from typing import Any import pandas as pd from anubis.models import Submission, Assignment from anubis.utils.cache import cache def get_submissions(course_id: str) -> pd.DataFrame: """ Get all submissions from visible assignments, and put them in a dataframe :return: """ # Get the submission s...
# jsb/socklib/partyline.py # # """ provide partyline functionality .. manage dcc sockets. """ __copyright__ = 'this file is in the public domain' __author__ = 'Aim' ## jsb imports from jsb.lib.fleet import getfleet from jsb.utils.exception import handle_exception from jsb.lib.threads import start_new_thread from j...
from __future__ import unicode_literals from builtins import str import six @six.python_2_unicode_compatible class TokenSet: """ A token set is used to store the unique list of all tokens within an index. Token sets are also used to represent an incoming query to the index, this query token set and ...
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021 # by the softwar...
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt import random def busqueda_local(solucion_inicial, evaluacion, obtener_vecinos, T_max, T_min, reduccion): """ Simulated Annealing. """ from random import random solucion_mejor = solucion_actual = soluc...
#!/usr/bin/python3 #-*-coding:utf-8-*- from threading import Thread import pymysql from Sqlcore import Sqlcore ''' 入口功能 ''' '''vmode打印显示模式full/standard/simple''' #生产环境的photo相册 conn = {"hostname":"xxxxxx.mysql.rds.aliyuncs.com","username":"forpython","password":"Ffu398fh_GFUPY","database":"dbuser","hostport":3708...
#!/usr/bin/env python import sys import os import shutil def cleanup_dump(dumpstr): cardfrags = dumpstr.split('\n\n') if len(cardfrags) < 4: return '' else: return '\n\n'.join(cardfrags[2:-1]) + '\n\n' def identify_checkpoints(basedir, ident): cp_infos = [] for path in os.listdir(b...
a, b = map(int, input()) if a <= 9 and b <= 9: ans = a * b else: ans = -1 print(ans)
# Test the frozen module defined in frozen.c. from test.test_support import TestFailed import sys, os try: import __hello__ except ImportError, x: raise TestFailed, "import __hello__ failed:" + str(x) try: import __phello__ except ImportError, x: raise TestFailed, "import __phello__ fail...
# Generated by Django 3.2.6 on 2021-08-21 12:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('education', '0021_alter_materialblocks_icon'), ] operations = [ migrations.AlterField( model_name='materialblocks', ...
from __future__ import annotations from typing import TYPE_CHECKING from openhab_creator import _ from openhab_creator.models.common import MapTransformation from openhab_creator.models.configuration.equipment.types.sensor import ( Sensor, SensorType) from openhab_creator.models.items import (DateTime, Group, Gro...
# -*- coding: utf-8 -*- """Library to easily manage Host Health""" from __future__ import division import logging import psutil import threading import time COLOR_GREEN = '#4caf50' COLOR_ORANGE = '#ff5722' COLOR_RED = '#f44336' CPU_THRESHOLD_WARNING = 70 CPU_THRESHOLD_DANGER = 85 duplex_map = { psutil.NIC_DUPL...
__author__ = 'Rob Edwards' import sys from matrices import blosum62 def score(a, b): """score dna as match/mismatch""" if a == b: return 1 return -1 def dna_score_alignment(seq1, seq2, gap_open=11, gap_extend=1): """ Generate a score for an alignment between two sequences. This does not ...
from libs.matrix_client.matrix_client.client import MatrixClient from libs.matrix_client.matrix_client.api import MatrixRequestError from libs.matrix_client.matrix_client.user import User from requests.exceptions import MissingSchema from helpers import setup_logger logger = setup_logger(__name__, 'info') class Clie...
import unittest import uuid from unittest.mock import patch from microsetta_private_api.model.interested_user import InterestedUser from microsetta_private_api.repo.interested_user_repo import InterestedUserRepo from microsetta_private_api.repo.transaction import Transaction from psycopg2.errors import ForeignKeyViola...
import binascii import socket import struct from twampy.utils import generate_zero_bytes, now from twampy.constants import TIMEOFFSET, TWAMP_PORT_DEFAULT, TOS_DEFAULT, TIMEOUT_DEFAULT import logging logger = logging.getLogger("twampy") class ControlClient: def __init__(self, server, port=TWAMP_PORT_DEFAUL...
from helpers import test_tools from graph import GraphRoutingProblem from dungeon import DungeonProblem
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import AuthIdentity, AuthProvider from sentry.testutils import APITestCase class DeleteUserIdentityTest(APITestCase): def test_simple(self): user = self.create_user(email="a@example.com") org =...
# # build the vocab/dictionary from outside to all related lexicons from __future__ import print_function import os import sys import argparse sys.path.append(".") sys.path.append("..") sys.path.append("../..") from neuronlp2 import utils from neuronlp2.io import get_logger, conllx_stacked_data # # Only use for ...
# Copyright 2021 Universität Tübingen, DKFZ and EMBL # for the German Human Genome-Phenome Archive (GHGA) # # 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/license...
def ones(l): #return l + [x + '_1' for x in l] #return sorted(l + [x + '_1' for x in l]) ret = [] for x in l: ret.append(x) ret.append(x + '_1') return ret # The complete primitive sets ffprims_fall = ones( [ 'FD', 'FDC', 'FDCE', 'FDE', '...
import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = 'django-pimp-my-filter', version = '0.1.1', ...
#!/usr/bin/env python # Python imports import matplotlib as plt import numpy as np import time import argparse # Other imports import srl_example_setup from simple_rl.tasks import GridWorldMDP from simple_rl.planning.ValueIterationClass import ValueIteration # INSTRUCTIONS FOR USE: # 1. When you run the program [eit...
import socket import time HOST='data.pr4e.org' PORT=80 mysock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) mysock.connect((HOST,PORT)) mysock.sendall(b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n') count=0 picture=b"" while True: data=mysock.recv(5120) if(len(data)<1): break time.slee...
#!/usr/bin/env python """ Tropical Cyclone Risk Model (TCRM) - Version 1.0 (beta release) Copyright (C) 2011 Commonwealth of Australia (Geoscience Australia) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the...
import pandas as pd import numpy as np from os import listdir import config def read(bound_file_path, compounds_file_path, adducts_file_path): ''' Read in excel files as pd.DataFrame objects ''' bound_df = pd.read_excel(bound_file_path) compounds_df = pd.read_excel(compounds_file_path) adduc...
#! /usr/bin/env python import onnx.backend import argparse import caffe2.python.workspace as c2_workspace import glob import json import numpy as np import onnx import caffe2.python.onnx.frontend import caffe2.python.onnx.backend import os import shutil import tarfile import tempfile import boto3 from six.moves.url...
# Copyright (c) 2018 Graphcore Ltd. All rights reserved. # This script is run by the release agent to create a release of PopTorch def install_release(release_utils, release_id, snapshot_id, version_str): # Tag must contain the string 'poptorch' to keep it unique. tag = "{}-poptorch".format(version_str) ...
import json import pytest from ermaket.api.database import DBConn from ermaket.api.scripts import ScriptManager from ermaket.api.system.hierarchy import Activation, Trigger, Triggers CHAIN_ID = 1 TEAPOT_ID = 2 ADD_ID = 3 ADD2_ID = 4 def login(client, user): return client.post( '/auth/login', data={ ...
from django.conf.urls import url from django.views.generic.base import RedirectView from tests.views import foo, foo_api urlpatterns = [ url(r"^api/foo/$", foo_api), url(r"^foo/$", foo), url(r"^bar/$", RedirectView.as_view(url="/foo/", permanent=False)), ]
from math import sqrt from django.test import TestCase from ..models import InstructionSet class InstructionSetModelTest(TestCase): def setUp(self): self.test_set = InstructionSet.objects.create(up=1, down=3, left=5, right=7) def test_model_fields(self): self.assertEqual(self.test_set.up, ...
from .site import SiteCommand from .platform import PlatformCommand from .system import SystemCommand AVAILABLE_COMMANDS = [SiteCommand(), PlatformCommand(), SystemCommand()]
# Generated by Django 2.0.8 on 2018-08-25 09:21 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('information_pages', '0004_auto_20180825_1114'), ] operations = [ migrations.AlterModelOptions( name='informationdocument', o...
""" This script is used to construct, test and analyze the various variants for digit addition and subtraction. """ import re import sys import subprocess import colorama # snippet construction def define_all(): global ADD_09_09, ADD_09_90, ADD_90_09, ADD_90_90 global SUB_09_09, SUB_90_09, SUB_09_90, SUB_90...
# -*- coding: utf-8 -*- """ Spyder Editor AutoGIS lesson 2 geopandas This is a temporary script file. """ import geopandas as gpd # set filepath fp = r'F:\GS\harrisab2\S18\GeoViz\autoGIS_2\Data\DAMSELFISH_distributions.shp' # read file using gpd.read_file() data = gpd.read_file(fp) # write first 50 r...
# -*- coding: utf-8 -*- from __future__ import division from pyevolve import G1DList, GSimpleGA, Selectors, Statistics from pyevolve import Initializators, Mutators, Consts, DBAdapters import os from math import log, log1p, exp from pyevolve import G1DList from pyevolve import GSimpleGA from pyevolve import Selectors ...
import datetime import random import matplotlib.pyplot as plt from graphpkg.live.graph import LiveTrend,LiveScatter # plt.style.use('') count1 = 0 cluster = 0.30 def func1(): global count1 count1 += 1 return datetime.datetime.now(), [random.randrange(1, 10) + count1,random.randrange(1,10)+ count1] def...
''' Created on 2016/9/20 :author: hubo ''' from __future__ import print_function from vlcp.server import main from vlcp.event import Client from vlcp.server.module import Module from vlcp.config import defaultconfig from vlcp.protocol.zookeeper import ZooKeeper, ZooKeeperConnectionStateEvent,\ ZooKeeperWatcherEven...
from mbdata import models from sqlalchemy import inspect from sqlalchemy.orm.session import object_session ENTITY_TYPES = { 'artist': models.Artist, 'label': models.Label, 'place': models.Place, 'release_group': models.ReleaseGroup, 'release': models.Release, 'url': models.URL, 'work': mod...
import enum class Encrypting: def __init__(self): encrypting_type = "" #szyfr wybrany w gui class Cipher(enum.Enum): NO_CIPHER = 1 CAESAR = 2 FERNET = 3 POLYBIUS = 4 RAGBABY = 5
from flask import Flask from flask import render_template from flask import request, jsonify import argparse import itertools import dateutil.parser import os from flask_sqlalchemy import SQLAlchemy from libs import gcal_client SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') app = Flask(__name__) app.conf...
#!/usr/bin/env python # import webapp2 import re from google.appengine.ext import ndb from google.appengine.ext import blobstore from google.appengine.api import users from google.appengine.ext.webapp import blobstore_handlers import logging import parsers import headers # This is the triple store api. # We have a n...
''' Created By ILMARE @Date 2019-3-1 ''' from bs4 import BeautifulSoup from urllib.request import urlretrieve import requests from PIL import Image import os import re totalCount = 0 pre_path = r"/home/ilmare/Desktop/FaceReplace/data/image/" class PhotoScrawler: def __init__(self, savePath, destUrl, maxPage): ...
from diary.models import Note from django.forms import Textarea, ModelForm from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.html import format_html from django.views.generic import ListView, CreateView class NoteListView(ListView): ...
# -*- coding: utf-8 -*- import os from lib.ipc import ActorProcess from lib.systray import SysTrayIcon from lib.utils import init_logging class UI(ActorProcess): def __init__(self, coordinator): super(UI, self).__init__() self.coordinator = coordinator def systray_quit(self, systray_...
# Copyright 2017 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...
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. # Copyright 2019 Kakao Brain # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this f...
import numpy as np import string wrd_fname = 'p042_words.txt' def gen_triang_list(elems = 1000): out_list = [] for x in xrange(1, elems): out_list.append((x*(x+1))/2) return out_list def word_to_sum(word): total_sum = 0 word = string.lower(string.strip(word)) base_sub = ord('a')-1 ...
from flask import Flask, jsonify from flask_marshmallow import Marshmallow from flask_bcrypt import Bcrypt from flask_cors import CORS from flask_restful import Api from flask_jwt_extended import JWTManager ma = Marshmallow() cors = CORS() bcrypt = Bcrypt() jwt = JWTManager() def create_app(config_object=None): ...
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- # bot_bcad_3.6.py import utilities, os, fnmatch, re async def membersDump(ctx): serverName = (f"*{ctx.message.guild.name.replace(' ', '-')}*") membersList = [] for file in os.listdir('./logs'): if fnmatch.fnmatch(file, 'members-server*'): ...
# Greedy class Solution: def maxProfit(self, prices): profit = 0 for i in range(len(prices) - 1): profit += max(0, prices[i + 1] - prices[i]) return profit if __name__ == "__main__": i = [7, 1, 5, 3, 6, 4] s = Solution() print(s.maxProfit(i))
# source code: binary_decoder.py # author: Lukas Eder # date: 13.02.2018 # # Descr.: # Userinput wird von ASCII in binaere Byte-Strings gewandelt oder umgekehrt. # Funktion Binaer zu Ascii def bin_read(binCode): for line in file: line_split = line.strip('\n').split(",") ...
#!/usr/bin/env python3 """main.py: The main file used to execute MindFull.""" __author__ = "Rhys Read" __copyright__ = "Copyright 2019, Rhys Read" import logging from display import Display logging.basicConfig(level=logging.DEBUG) class Main(object): def __init__(self): self.__display = Display() ...
from Utils.alerter import send from Utils.urlShortener import short import discord from discord.ext import commands import config class AntiCaps(commands.Cog): def __init__(self, client): self.client = client self.title = "Anti-Caps System" self.type = config.CAPS_TYPE if self.t...
import numpy as np def get_quantization_matrix(quality: int = 100) -> np.ndarray: """ Get quantization matrix denpends on quality. Args: quality: quality of quantization Returns: quantiazation matrix """ # quantization matrix q = [[16, 11, 10, 16, 24, 40, 51, 61], ...