content
stringlengths
5
1.05M
from lib.base import BaseGithubAction from lib.formatters import repo_to_dict __all__ = [ 'GetRepoAction' ] class GetRepoAction(BaseGithubAction): def run(self, user, repo, base_url): if base_url == None: self._reset(user) else: self._reset(user+'|'+base_url) u...
from unittest import TestCase from two_thinning.strategies.mean_thinning_strategy import MeanThinningStrategy class TestMeanThinningStrategy(TestCase): def __init__(self): super().__init__() self.strategy = MeanThinningStrategy(n=3, m=5) def test_decide(self): self.fail() def tes...
from datetime import datetime import logging from django.conf import settings from django.core.cache import cache from django.http import JsonResponse from django.views.generic import TemplateView import pytz import requests log = logging.getLogger(__file__) class HomePageView(TemplateView): """ Handles t...
import logging from flask import request, url_for from telegram import Update from backend import DEVELOPMENT_MODE, TELEGRAM_TOKEN, app, bot, update_queue LOG = logging.getLogger(__name__) last_update_id = 0 @app.route(f"/{TELEGRAM_TOKEN}/", methods=["POST"]) def telegram_webhook(): update = Update.de_json(re...
from django.contrib.auth.models import User from django.test import TestCase from django.core.management import call_command from workflow.models import Country from factories.workflow_models import CountryFactory, UserFactory, TolaUserFactory, CountryAccess class TestUpdateUserPermissions (TestCase): def setUp...
from wifi import Cell, exceptions from time import sleep from sys import argv import sqlite3 import os EVIL_TWIN_DB = "src/python/evil_twin/evil_twin.db" def scan_for_evil_twin(time, adapter): conn = sqlite3.connect(EVIL_TWIN_DB) cursor = conn.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS LOG (...
from srcode import app import os, click def startup(app): @app.cli.group() def translate(): """Translation and localization commands for easier translations. Parent command that provides a base for other commands below""" pass @translate.command() @click.argument('lang') def update...
"""Run a simple test of the Cusser class.""" import curses import sys from functools import reduce from ._misc import ( _SUPPORTED_ATTRIBUTE_TAGS, _SUPPORTED_COLOR_TAGS, _app, _clear_line, _clear_screen, _move, _step, ) if __name__ == "__main__": if len(sys.argv) < 2: print( ...
n, c = map(int, input().split()) array = [] for i in range(n): array.append(int(input())) array.sort() def binary_search(array, start, end): while start <= end: mid = (start + end) // 2 current = array[0] count = 1 for i in range(1, len(array)): if array[i] >= cu...
# -*- coding:utf-8 -*- # @Time: 2021/1/30 11:36 # @Author: Zhanyi Hou # @Email: 1295752786@qq.com # @File: pythonedit.py import logging import time import re from typing import Tuple, List, TYPE_CHECKING from qtpy.QtGui import QTextCursor, QMouseEvent, QKeyEvent, QTextBlock from qtpy.QtWidgets import QLabel, QListWidg...
"""LintPlaybook version""" __version__ = '0.1.dev1'
import os.path from django import template from django.utils.html import format_html from django.template.defaultfilters import filesizeformat from django.template.loader import get_template register = template.Library() @register.filter def attachment_link(attachment): kwargs = { 'href': attachment.att...
from .item import Item from .wall import Wall from .decoration import Decoration from .item_grid import ItemGrid from .player import Player from .person import Person from .enemy import Enemy from .door import Door from .item_weapon import ItemWeapon from .item_ammo import ItemAmmo from .item_score import ItemScore c...
#!/usr/bin/python38 import hashlib import lxml import re import requests from lxml import etree from libmysql_utils.mysql8 import mysqlHeader, mysqlBase from sqlalchemy import Column, String, Integer, Float, Date, Text from sqlalchemy.ext.declarative import declarative_base from libutils.log import Log __version__ = ...
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Li...
from preprocessing_utilities import create_and_save_uniques, load_uniques_create_dict_map from Scripts.utilities import start_correct_cluster, read_dataset, save_dataset, parse_args from preprocessing_utilities import dict_path, temp_output_path, dataset_path import numpy as np import dask import dask.dataframe as dd ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import gin.tf slim = tf.contrib.slim gin.constant('networks.STACK_SIZE_1', 1) gin.constant('networks.STACK_SIZE_4', 4) gin.constant('networks.OBSERVATION_DTYPE_FLOA...
"""Initial Build Revision ID: 34935013ab33 Revises: Create Date: 2020-03-10 23:05:03.634539 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "34935013ab33" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto genera...
import re import PyPDF2 import pandas as pd """ """ # Setting the file path pdf_path = 'ED_8_PETROBRAS_PSP1_2021_RES_FINAL_OBJ_CONV_TITULOS.PDF' # Reading the PDF file with PyPDF2 with open(pdf_path, mode='rb') as f: reader = PyPDF2.PdfFileReader(f) # Getting the number of pages num_pages = reader.getN...
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or th...
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT """ This file defines classes for job handlers specific for Testing farm """ import logging from datetime import datetime from typing import Optional from celery import signature from packit.config import JobConfig, JobType from packit.con...
from django.db import models class AnswerSetUniqueManager(models.Manager): def get_queryset(self): return super(AnswerSetUniqueManager, self).get_queryset().filter(is_duplicate=False)
from flask import Flask from flask_bootstrap import Bootstrap def create_app(): app = Flask(__name__) Bootstrap(app) return app app = create_app() app.config['WTF_CSRF_ENABLED'] = True from cantina import views
#!/usr/bin/env python import os import sys import gzip from Bio import SeqIO modified = [] with gzip.GzipFile( sys.argv[1] ) as fh: for record in SeqIO.parse( fh, "fasta" ): record.id += "|" + str( len( record ) ) modified.append( record ) for record in modified: record.name, record.descripti...
""" Defines the ChacoShellError class. """ class ChacoShellError(RuntimeError): """ Error raised by the Chaco shell. """ pass # EOF
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013-2015 clowwindy # # 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 requi...
""" Plugin for file-based transformers (bash and Docker transformers) NOTE: there are some semantic differences with executor.py of the bash- and docker-transformers for local job execution as implemented by Seamless itself. This is because in Jobless, we are dealing with buffers (potentially already in a file) and ...
#!/usr/bin/env python import pygame from sprite import * from megaman_object import * import universal_var import timer from mega_stack import Stack import projectile class Death_orb(projectile.Projectile): all_orbs_lst = [] all_orbs_stack = Stack() def __init__(self): x, y = 0, 0 ...
"""! @author atomicfruitcake @date 2019 """
import argparse import multiprocessing from datetime import datetime from course_lib.Base.Evaluation.Evaluator import * from course_lib.Base.IR_feature_weighting import TF_IDF from course_lib.GraphBased.P3alphaRecommender import P3alphaRecommender from course_lib.GraphBased.RP3betaRecommender import RP3betaRecommender...
# Generated by Django 2.0.13 on 2019-05-28 14:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [("django_geosource", "0002_auto_20190524_1137")] operations = [ migrations.AlterModelOptions( name="source", options={"permissions": (("ca...
from unittest import TestCase from main import strip_quotes class TestStripQuotes(TestCase): def test_strip_quotes_removes_quotes_from_string_margins(self): self.assertEqual('string_with quotes', strip_quotes('\'string_with quotes\'')) def test_strip_quotes_removes_double_qu...
from sys import argv script, data, setor, tipo, usuario, descricao, finalizado = argv contador = open('contador.dat', 'r') contadorInt = int(contador.read()) contadorInt = contadorInt + 1 contadorStr = str(contadorInt) contadorUpt = open('contador.dat', 'w') contadorUpt.write(contadorStr) contadorUpt.close target =...
import json import random import sys import numpy as np import torch import unidecode from tqdm import tqdm __all__ = [ "Dataloader", ] ENTITY_PAIR_TYPE_SET = set( [("Chemical", "Disease"), ("Chemical", "Gene"), ("Gene", "Disease")]) def map_index(chars, tokens): # position index mapping from character ...
class Credentials(): # users list credentials_list = [] ''' initialize a class ''' def __init__(self,Fname,Sname,username,password,email): ''' users class 'blueprint' ''' self.Fname = Fname self.Sname = Sname self.username = username self.password = password ...
import sys SIX_TAB = { # six.moves: (py2, py3) "configparser": ("ConfigParser", "configparser"), "copyreg": ("copy_reg", "copyreg"), "cPickle": ("cPickle", "pickle"), "cStringIO": ("cStringIO", "io"), "dbm_gnu": ("gdbm", "dbm.gnu"), "_dummy_thread": ("dummy_thread", "_dummy_thread"), "...
from functools import update_wrapper import typing as t import click from aprsd import config as aprsd_config from aprsd import log F = t.TypeVar("F", bound=t.Callable[..., t.Any]) common_options = [ click.option( "--loglevel", default="INFO", show_default=True, type=click.Choic...
# Generated by Django 3.2 on 2021-04-08 17:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'), ('cadastres', '0001_initial'), ] operations = [ migra...
from math import ceil, log #1 ip address ipAddress = input("Enter ip Address: ") #2 separated in 4 parts => string and binary firstPart, secondPart, thirdPart, fourthPart = ipAddress.split(".") ipAddressFourParts = [int(firstPart), int(secondPart), int(thirdPart), int(fourthPart)] binaryipAddressFourParts = l...
# Generated by Django 3.0.2 on 2020-06-29 23:19 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('leagues', '0002_auto_20200629_2319'), ('teams', '0001_initial'), ] operatio...
from itertools import product a,b=map(int, input().split()) c=(list(map(int, input().split()))[1:] for _ in range(a)) r=map(lambda x: sum(i**2 for i in x) % b, product(*c)) print(max(r))
import logging import os import re from collections import Counter import numpy as np from data.data_iterator import ids2seq def load_file(path): """Load file formated with one sentence per line and tokens separated by spaces.""" with open(path, "r", encoding="utf8") as file: outputs = [line.strip()...
import numpy as np def get_phaselc(t, p, data, v_num): return 1.+p.amp1[v_num]*np.cos(2.*np.pi*(t-p.theta1[v_num])/p.per[v_num]) + p.amp2[v_num]*np.cos(4.*np.pi*(t-p.theta2[v_num])/p.per[v_num])
from .LayoutManager import LayoutManager
""" """ import numpy as np from ..axis_ratio_model import monte_carlo_halo_shapes def _enforce_constraints(b_to_a, c_to_a, e, p): assert np.all(b_to_a > 0), "All elements of b_to_a must be strictly positive" assert np.all(c_to_a > 0), "All elements of c_to_a must be strictly positive" assert np.all(b_to_a...
import os import json import numpy as np import cv2 import matplotlib.pyplot as plt root_dir = '../FS2K' root_dir_photo = os.path.join(root_dir, 'photo') root_dir_sketch = os.path.join(root_dir, 'sketch') photo_paths = [] for photo_dir in os.listdir(root_dir_photo): photo_dir = os.path.join(root_dir_photo, photo...
from tkinter import * class BillCalculator: def __init__(self): window = Tk() window.title("Bill Calculator") # input fields Label(window, text = "How much is the bill?").grid(row = 1,column = 1, sticky = W) Label(window, text = "How many people?").grid(ro...
import sys try: from io import StringIO from io import BytesIO except ImportError: from StringIO import StringIO as StringIO from StringIO import StringIO as BytesIO import unittest import mitogen.core from mitogen.core import b import testlib #### #### see also message_test.py / PickledTest #### ...
# Copyright 2015 Google 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 applicable law or ...
# coding=UTF-8 # ex:ts=4:sw=4:et=on # Copyright (c) 2013, Mathijs Dumon # All rights reserved. # Complete license can be found in the LICENSE file. import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) from math import sqrt import numpy as np import scipy from deap import cma, base, c...
from __future__ import print_function, division, absolute_import import functools import sys # unittest only added in 3.4 self.subTest() if sys.version_info[0] < 3 or sys.version_info[1] < 4: import unittest2 as unittest else: import unittest # unittest.mock is not available in 2.7 (though unittest2 might cont...
from random import randint from forex_python.converter import CurrencyRates import datetime print('\nCONVERSOR "UNIVERSAL"\n') op = int(input('Escolha o que deseja fazer:\n' '1. TEXTO\n' '2. MEDIDAS\n' '3. MOEDAS\n' '4. FÓRMULAS\n' '5. NÚMEROS A...
import pytest from zeroae.rocksdb.c import db as rdb from zeroae.rocksdb.c import pinnableslice @pytest.fixture def db(rocksdb_db, rocksdb_writeoptions): rdb.put(rocksdb_db, rocksdb_writeoptions, "key", "value") yield rocksdb_db @pytest.fixture def slice(db, rocksdb_readoptions): rv = rdb.get_pinned(db...
"""Stream type classes for tap-smartsheet.""" from typing import Any, Dict, Optional, Union, List, Iterable from singer_sdk import typing as th # JSON Schema typing helpers from singer_sdk.plugin_base import PluginBase as TapBaseClass from singer.schema import Schema from singer_sdk.typing import JSONTypeHelper fro...
from django.conf.urls import patterns, include, url from django.contrib import admin import views urlpatterns = patterns('', url(r'^viewall_contest/(?P<group_id>\d+)/$', views.get_running_contest, name='viewall_contest'), url(r'^viewall_archive/(?P<group_id>\d+)/$', views.get_ended_contest, name='viewall_archi...
#!/user/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from src.libraries.myMathLib import point_to_segment_distance, euclidean_distance_3d, lineseg_dist, distance_numpy def main(): expected = 5 a0 = np.array([3, 1, -1]) a1 = np.array([5, 2, 1]) c = np.array([0, 2, 3]) print(lineseg_...
from rest_framework import serializers from core_model.models import Appointment class AppointmentSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = '__all__' read_only_fields = ( 'id', 'end_date' )
from contextlib import AsyncExitStack, ExitStack from types import TracebackType from typing import Any, Dict, Optional, Type, Union from di._utils.scope_map import ScopeMap from di._utils.types import CacheKey, FusedContextManager from di.api.scopes import Scope class ContainerState: __slots__ = ("cached_values...
#!/usr/bin/env python # Copyright (c) 2018 Trail of Bits, 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 applic...
"""Test cases for the location module.""" from pytest_mock import MockFixture from rdflib import Graph from rdflib.compare import graph_diff, isomorphic from skolemizer.testutils import skolemization from datacatalogtordf import Location def test_to_graph_should_return_identifier_set_at_constructor() -> None: ""...
# -*- coding: utf8 -*- # Copyright 2019 JSALT2019 Distant Supervision Team # # 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 # # U...
from bench import bench print(bench(10, '', ''' s = [] for i in range(100000): s.append(i) for _ in range(100000): s.pop() '''))
import os import numpy as np from skimage.io import imread from skimage.exposure import adjust_gamma class DataGenerator(): """Reads dataset files (images & annotations) and prepare training & validation batches""" def __init__(self, batch_size, validation_size, directory, train_test='train'): """Loa...
''' ------------------------------------------------------------------------ Household functions for taxes in the steady state and along the transition path.. This file calls the following files: tax.py ------------------------------------------------------------------------ ''' # Packages import numpy as np from...
from .extension import *
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import sortedm2m.fields class Migration(migrations.Migration): dependencies = [ ('photologue', '0006_auto_20141028_2005'), ] operations = [ migrations.AlterField( model_n...
# -*- coding: utf-8 -*- # # Copyright (c) 2020~2999 - Cologler <skyoflw@gmail.com> # ---------- # # ---------- from typing import * import os import sys import traceback import re import click from click_anno import click_app from click_anno.types import flag from fsoopify import NodeInfo, NodeType, FileInfo, Directo...
from yacs.config import CfgNode as CN _C = CN() _C.DEVICE = 'cuda' _C.MODEL = CN() _C.MODEL.SCALE_FACTOR = 1 _C.MODEL.DETECTOR_TYPE = 'u-net16' # 'PSPNet' _C.MODEL.SR = 'DBPN' _C.MODEL.UP_SAMPLE_METHOD = "deconv" # "pixel_shuffle" _C.MODEL.DETECTOR_DBPN_NUM_STAGES = 4 _C.MODEL.OPTIMIZER = 'Adam' # SGD _C.MODEL.NUM_CL...
import streamlit as st from streamlit_option_menu import option_menu from prediction import show_predict_page from explore import show_explore_page from PIL import Image st.set_page_config( page_title="Predict Heart Disease", ) with st.sidebar: page = option_menu("", ["Facts and figures", 'Predict'], ...
from config.settings.base import * # install gdal in virtualenv: VIRTUAL_ENV = os.environ["VIRTUAL_ENV"] OSGEO_VENV = os.path.join(VIRTUAL_ENV, "Lib/site-packages/osgeo") GEOS_LIBRARY_PATH = os.path.join(OSGEO_VENV, "geos_c.dll") GDAL_LIBRARY_PATH = os.path.join(OSGEO_VENV, "gdal302.dll") PROJ_LIB = os.path.join(VIRTU...
#!/usr/bin/env python3 # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Test program for tiny_par_unittest.py.""" import sys def main(): if len(sys.argv) > 2: print(' '.join(sys.argv[2:])) ...
from django.db.models.signals import pre_save,post_save from django.dispatch import receiver import geoLocApp.models import geoLocApp.distance @receiver(pre_save,sender=geoLocApp.models.Coordonnee,dispatch_uid="only_before_registered") def setDistance(sender, **kwargs): coordonnee = kwargs["instance"] ...
import numpy as np from torch import nn from torch.nn import functional as F from model.utils.bbox_tools import generate_anchor_base from model.utils.creator_tool import ProposalCreator def normal_init(m, mean, stddev): m.weight.data.normal_(mean, stddev) m.bias.data.zero_() # Region Proposal Network struc...
import numpy as np from patsy import dmatrix from pywt import wavedec, waverec, dwt_max_level from ..blocks import block_apply from ...channel_map import ChannelMap from ...devices.electrode_pinouts import get_electrode_map def poly_residual(field: np.ndarray, channel_map: ChannelMap, mu: bool=False, order: int=2): ...
"""Clean processed folder. Usage: clean [--output_dir=<output_dir>] [<directory>] """ import argparse import pathlib import shutil import os def main(source_dir): if source_dir.exists(): shutil.rmtree(source_dir) zip_path = source_dir.parent / "manuscript.zip" if zip_path.exists(): os.re...
# This filter procedurally generates 4 structures within the selection box within defined limits # This filter: mcgreentn@gmail.com (mikecgreen.com) import time # for timing from math import sqrt, tan, sin, cos, pi, ceil, floor, acos, atan, asin, degrees, radians, log, atan2, acos, asin from random import * from numpy...
"""Basic toolkit for asynchronous task communication / management using friendly threaded queues.""" # USE EXAMPLES & TESTING TO BE COMPLETED. from threading import Thread from multiprocessing import Pool, Process from multiprocessing.context import TimeoutError as TimesUpPencilsDown from multiprocessing import Queue ...
import numpy as np import pandas as pd import pytest from pyabc.storage.dataframe_bytes_storage import df_from_bytes, df_to_bytes @pytest.fixture( params=[ "empty", "int", "float", "non_numeric_str", "numeric_str", "int-float-numeric_str", "int-float-non_nu...
""" Provide a sphinx extension to generate widgets from code: ada. A role :code-config: must be seen before parsing the first code: block, for instance :code-config:`run_button=True;prove_button=False;accumulate_code=True` See doc in the function codeconfig. Code accumulation: cancel it with an empty :code-confi...
r""" Wrapper class for abelian groups This class is intended as a template for anything in Sage that needs the functionality of abelian groups. One can create an AdditiveAbelianGroupWrapper object from any given set of elements in some given parent, as long as an ``_add_`` method has been defined. EXAMPLES: We crea...
#!/usr/bin/env python3 """ An autogenerated testfile for python. """ import unittest from unittest.mock import patch from io import StringIO import re import os import sys from unittest import TextTestRunner from examiner import ExamTestCase, ExamTestResult, tags from examiner import import_module, find_path_to_assign...
# Copyright (c) 2013, 2017 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the function...
#!/usr/bin/env python # coding: utf-8 class Default(object): def __init__(self): import re self.__pattern = re.compile('\s+') def segment(self, text): from salada import language sequence = self.__pattern.split(text) last_index = len(sequence) - 1 segments =...
import re, json, io thesaurus = [] with open('th_en_US_v2.dat') as fp: encoding = fp.readline().rstrip('\n') lineNumber = 1 numberOfMeanings = 0 for line in fp: lineNumber += 1 line = line.rstrip('\n').split("|") if len(line) == 2 and not (line[0].startswith("(") and line[0].endswith(")")): word = line[0...
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """Pure-Python RSA implementation.""" from .cryptomath import * from .asn1parser import ASN1Parser from .rsakey import * from .pem import * class Python_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=...
from flask import Flask, render_template, request, redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db' db = SQLAlchemy(app) class BlogPost(db.Model): id = db.Column(db.Integer, primary_key=True) title...
import unittest from main import parse_data from models import Marker class TestParseData(unittest.TestCase): def setUp(self): self.marker_dummy = dict(type=1, title="test title", description="test description", latitude=1, longitude=1) self.bad_marker_dummy = dict(type=1, title="No properties") ...
# Create your views here. from django.http import HttpResponse, HttpResponseNotFound from django.shortcuts import render from django.shortcuts import redirect from OctaHomeDeviceInput.models import * from OctaHomeCore.views.base import * from OctaHomeCore.models import * from OctaHomeLights.models import * from OctaH...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' main.py Main script for AsyncioProp. usage: python3 main.py [-h] [-s SERVER] [-p PORT] [-d] [-l LOGGER] optional arguments: -h, --help show this help message and exit -s SERVER, --server SERVER change MQTT server host -p PORT, --port PORT change MQTT serv...
import sc2 from sc2.ids.unit_typeid import UnitTypeId from sc2.units import Units from sc2.position import Point2 class WorkerRushBot(sc2.BotAI): """ - Worker Rush """ def __init__(self): super()._initialize_variables() self.close_to_enemies_base = False self.all_retreat = Fal...
class Node: def __init__(self, value): self.value = value self.next = None def add(self, value): self.next = Node(value) def reverse(self): cur = self new = cur.next cur.next = None # new tail? while new is not None: prev = cur ...
#!/bin/python import unittest from types import SimpleNamespace from sap import get_logger import sap.errors import sap.adt from mock import Connection, Response from fixtures_adt_package import GET_PACKAGE_ADT_XML from fixtures_adt_repository import (PACKAGE_ROOT_NODESTRUCTURE_OK_RESPONSE, ...
import json # DB->db.json内にあるデータベースへのログインデータの読み込みを行う from peewee import * #データベースの操作に必要 def db_login(): with open('./DB/db.json', 'r', encoding='utf-8') as f: db_set = json.load(f) db = MySQLDatabase( host=db_set['mariadb']['host'], port=db_set['mariadb']['port'], user=d...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : regression03.py @Time : 2019/07/15 20:47:44 @Author : xiao ming @Version : 1.0 @Contact : xiaoming3526@gmail.com @Desc : 岭回归以及逐步线性回归 @github : https://github.com/aimi-cn/AILearners ''' # here put the import lib from matplotlib.font_m...
# Django from django.contrib import admin # Circle from circles.models import Circle @admin.register(Circle) class CircleAdmin(admin.ModelAdmin): list_display = ('slug_name', 'name', 'is_public', 'verified', 'is_limited', 'members_limit') search_fields = ('slug_name', 'name') list_filt...
from geode import * from numpy import * def test_sse(): random.seed(3871) for i in xrange(10): x = random.randn(2) assert all(x==sse_pack_unpack(x))
""" Party endpoints """ from flask import Flask, make_response, abort, jsonify, Blueprint,request from app.api.v2.models import party_model from app.api.v2.models import user_model from app.api.v2 import database from app.api.v2.utils.verify import verify_tokens from app.api.v2.utils.validator import validate_party...
import tkinter, passwd, _thread class Interface(): def __init__(self, name, size): self.Generator = passwd.Password() self.size = size self.root = tkinter.Tk() self.root.title(name) self.winfo_screen = [self.root.winfo_screenwidth()//2, self.root.winfo_screenheight()//2] ...
""" Youtube Tag --------- This implements a Liquid-style youtube tag for Pelican, based on the jekyll / octopress youtube tag [1]_ Syntax ------ {% youtube id [width height] %} Example ------- {% youtube dQw4w9WgXcQ 640 480 %} Output ------ <span class="videobox"> <iframe width="640" height="480" ...
""" https://fe8ebede-836e-432b-ad74-af1265de3de2.mock.pstmn.io/rangos1 <ConsultaRangosResult> <Mensaje>OK</Mensaje> <Rangos> <Rango> <Desde>501</Desde> <Hasta>540</Hasta> </Rango> <Rango> <Desde>551</Desde> <Hasta>600</Hasta> </Ran...