content
stringlengths
5
1.05M
# Helper module try: from .helper import H except: from helper import H # Settings variables try: from . import settings as S except: import settings as S # View module try: from . import view as V except: import view as V # Modules to be imported from package when using * __all__ = ['config','dbgp','H','load'...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: modules/planning/proto/pad_msg.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protob...
from django.utils.translation import ugettext as _ from misago.core.mail import build_mail, send_messages from misago.threads.permissions import can_see_post, can_see_thread from . import PostingEndpoint, PostingMiddleware class EmailNotificationMiddleware(PostingMiddleware): def __init__(self, **kwargs): ...
from .types import ( read_functype, read_globaltype, read_memtype, read_tabletype, read_valtype, ) from .values import get_vec_len, read_name, read_uint from .instructions import read_expr def read_customsec(buffer: object, length: int) -> tuple: """Read a custom section from buffer.""" # ...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # 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 ...
#! /usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup from xkbgroup.version import VERSION def read_readme(): with open("README.rst") as f: return f.read() setup( name="xkbgroup", version=VERSION, description="Query and change XKB layout state", long_description=r...
#!/usr/bin/env python3 # -*- CoDing: utf-8 -*- """ Created on May 22 2019 Last Update May 22 2019 @author: simonvanvliet Department of Zoology University of Britisch Columbia vanvliet@zoology.ubc.ca This recreates the data and figure for figure 4 By default data is loaded unless parameters have changes, to rerun mod...
"""Internal API endpoint constant library. _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | ...
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Optional import pygame from snecs.typedefs import EntityID from scripts.engine.core.constants import GameState, GameStateType from scripts.engine.world_objects.gamemap import Gamemap if TYPE_CHECKING: from typing import TYP...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ################################################################################ # # Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved. # # File: tools/timer.py # Date: 2019/10/12 15:12:02 # Author: hehuang@baidu.com # #################################################...
class Scene: """ Scene has all the information needed for the ray tracing engine """ def __init__(self, camera, objects, width, height): self.camera = camera self.objects = objects self.width = width self.height = height
""" This script converts NeSys .xyz files with coordinates specified in the local coordinate system for the pontine nuclei defined by Leergaard et al. 2000 to Waxholm Space coordinates for the rat brain (in voxels). """ # pylint: disable=C0103 import os import random random.seed() # - - - - - - - - - - - - ...
import asyncio import aiohttp import time URL = 'https://mofanpy.com/' async def job(session): response = await session.get(URL) return str(response.url) async def main(loop): async with aiohttp.ClientSession() as session: tasks = [loop.create_task(job(session)) for _ in range(2)] finished, unfinished = await...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'telaAdd.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django import forms import six class AjaxForm(forms.Form): def as_json(self, general_errors=[]): field_errors = dict((key, [six.text_type(error) for error in errors]) ...
import math import torch.nn as nn from basicsr.utils.registry import ARCH_REGISTRY cfg = {'A': [64, 128, 128, 128, 128, 128]} def make_layers(cfg, scale, batch_norm=False): layers = [] in_channels = 3 for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import time from ranking.management.modules.common import REQ, BaseModule class Statistic(BaseModule): API_RANKING_URL_FORMAT_ = 'https://dmoj.ca/api/contest/info/{key}' def __init__(self, **kwargs): super(Statistic, self).__init__(**kwargs)...
"""Functional test of 'dtool tag' CLI command.""" from click.testing import CliRunner from . import tmp_dataset_fixture # NOQA def test_tag_basic(tmp_dataset_fixture): # NOQA from dtool_tag.cli import tag runner = CliRunner() result = runner.invoke(tag, [ "set", tmp_dataset_fixture....
import os import sys import unittest from mock import Mock sys.path.append('../../') import blng.Voodoo class TestVoodoo(unittest.TestCase): def setUp(self): self.maxDiff = 400000 def _get_session(self): self.subject = blng.Voodoo.DataAccess('crux-example.xml') self.root = self.subj...
import unittest import zserio from testutils import getZserioApi class ChoiceBit4RangeCheckTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, "with_range_check_code.zs", extraArgs=["-withRangeCheckCode"]).choice_bit4_range_check ...
#! /usr/bin/python import sys import re from os import environ, linesep import csv KUBEVIRT_CLIENT_GO_SCHEME_REGISTRATION_VERSION = 'v1' def get_env(line): env = line[:line.find('=')] return f'{env}={environ.get(env)}' def get_env_file(outdir, file_format='txt'): rgx = re.compile('^[^ #]+=.*$') if ...
# -*- coding: utf-8 -*- """ utils.py ~~~~~~~~~~~~~ Author: Pankaj Suthar """ class Logger: def __init__(self, log_handler, name, entry_identifier=">>>>", exit_identifier="<<<<", log_time=False): self.log_handler = log_handler self.name = name self.entry_identifier = entry_identi...
# -*- coding: utf-8 -*- from hist import axis def test_axis_names(): """ Test axis names -- whether axis names work. """ assert axis.Regular(50, -3, 3, name="x0") assert axis.Boolean(name="x_") assert axis.Variable(range(-3, 3), name="xx") assert axis.Integer(-3, 3, name="x_x") assert...
import json from flask import Flask, request, current_app, render_template, redirect, url_for from signinghub_api import SigningHubAPI # Create a web application with Flask app = Flask(__name__) # Copy local_settings.py from local_settings_example.py # Edit local_settings.py to reflect your CLIENT_ID and CLIENT_SECRE...
# Objectives and constraints functions (Aug. 04, 2021) import math import numpy as np def objective(var_o): #objetive functions Weibull #confiabilidade gamma_ = theta = t = int(math.floor(var_o.copy())) r_t = math.exp(-((t/theta)**(gamma_))) #custo c_m = 1000 c_r = 2500 ...
import tqdm import os import json import re import itertools import math import matplotlib.pyplot as plt datasetFolder = "../dataset/PigData/" experiment = "pig5_v4" valNbEntities = [ 3, 6, 10 ] ######################################################################################## for nbEntities in valNbEntities...
import scrapy from ..items import DaGroup7Item from scrapy.loader import ItemLoader class TilesSpider(scrapy.Spider): name = 'tiles' allowed_domains = ['magnatiles.com'] start_urls = ['http://magnatiles.com/products/page/1/'] def parse(self, response): for p in response.css('ul.products li')...
''' https://www.hackerrank.com/challenges/prime-date/submissions/code/102871849 Debug the given function findPrimeDates and/or other lines of code, to find the correct lucky dates from the given input. Note: You can modify at most five lines in the given code and you cannot add or remove lines to the code. ''' import...
################################################################################ # Modules and functions import statements ################################################################################ import pdb from helpers.app_helpers import * from helpers.page_helpers import * from helpers.jinja2_helpers import ...
import cv2 import pandas as pd import numpy as np from webcolors import hex_to_rgb from talking_color.algorithms.eucledian_rgb import EucledianRGB class EucledianHSV(EucledianRGB): color_space = 'HSV' def _get_frame_in_color_space(self, frame): return cv2.cvtColor(frame, cv2.COLOR_BGR2HSV_FULL) ...
#!/usr/bin/env python3 """ A client for fuzzbucket. Configuration is accepted via the following environment variables: FUZZBUCKET_URL - string URL of the fuzzbucket instance including path prefix FUZZBUCKET_LOG_LEVEL - log level name (default="INFO") Optional: FUZZBUCKET_CREDENTIALS - credentials str...
import asyncio from .middleware import MiddlewareManager class ResultMiddlewareManager(MiddlewareManager): """ Responsibilities: * Execute all middlewares that operate on incoming results (output from Spider). .. method:: process_item(item, logger, spider) This method is called for each result pro...
#!/usr/bin/python3 import simpy from workload import Workload from scheduler import Scheduler from cluster import Cluster import argparse import yaml import json from os import path import subprocess parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='path to the configuration file for run...
import os import sys import argparse import numpy as np import vespa.common.util.export as util_export import vespa.common.util.time_ as util_time import vespa.common.wx_gravy.common_dialogs as common_dialogs import vespa.common.mrs_data_raw as mrs_data_raw DESC = \ """This utility converts single voxel MRS data ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from itertools import count from typing import Iterable, Iterator, List, Union from .event import ActualEvent, AtomEvent, CascadeEvent from .event_linked_list import EventLinkedList from .event_state import EventState def _pop(cntr: List[Actual...
from setuptools import setup, find_namespace_packages setup( name="nmcipher.cli", version="0.0.6", author="Neil Marshall", author_email="neil.marshall@dunelm.org.uk", description="A command line parser package for use with basic encryption algorithms", packages=find_namespace_packages(include=[...
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the MIT license. # See the LICENSE file in the project root for more information. from ..commonlib.collection_util import is_empty, unzip from .clr_types import AbstractTraceGC from .enums import ( ...
from setuptools import setup, find_packages requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_debugtoolbar', 'waitress' ] setup(name='abomid', packages=find_packages(), install_requires=requires, entry_points="""\ [paste.app_factory] main = abomid:main """, ...
import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread(r"..\lena.jpg", 0) template = cv2.imread(r"..\lena_eyes.png", 0) tw, th = template.shape[::-1] rv = cv2.matchTemplate(img, template, cv2.TM_CCOEFF) minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(rv) topLeft = maxLoc bottomRight = (topLeft[0...
#!/usr/bin/env python3 from pyautogui import alert as pag_alert from pyautogui import click, position, rightClick, moveTo from time import sleep pag_alert("Ok?") prev_pos = position() click(282, 132) sleep(1) rightClick(1370, 229) click(1350, 229) moveTo(prev_pos)
# Copyright (c) 2018 Danilo Vargas <danilo.vargas@csiete.org> # See the COPYRIGHT file for more information from __future__ import annotations import os from cowrie.shell.command import HoneyPotCommand from cowrie.shell.fs import A_NAME commands = {} class Command_du(HoneyPotCommand): def message_help(self): ...
from SimpleTextureAtlas import make_atlas from PIL import Image import os def list_files(directory): for path in os.listdir(directory): path = os.path.join(directory, path) if os.path.isfile(path): yield path if os.path.isdir(path): for new_path in ...
#!/usr/bin/env python LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz" UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" LOWER_ACCENTS = "âêîôûäëïöüàùèéç" UPPER_ACCENTS = "ÂÊÎÔÛÄËÏÖÜÀÙÈÉÇ" ACCENTS = "âêîôûäëïöüàùèéçÂÊÎÔÛÄËÏÖÜÀÙÈÉÇ" LOWER_ACCENTS_TRANS = str.maketrans...
from economic.account_entries import AccountEntry from economic.query import QueryMixin from economic.serializer import EconomicSerializer class AccountingYear(EconomicSerializer, QueryMixin): base_url = "https://restapi.e-conomic.com/accounting-years/" def __unicode__(self): return u"Accounting year...
from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score import numpy as np import time import argparse from lib.in_subject_cross_validation import cross_validate_dataset ## # cross_validate_per_subject_rfe: Performs cross validation on a per-subjec...
# -*- coding: utf-8 -*- """ @author: WZM @time: 2021/1/29 15:44 @function: """ import torch import torch.nn as nn import torchvision # print("PyTorch Version: ", torch.__version__) # print("Torchvision Version: ", torchvision.__version__) __all__ = ['DenseNet121', 'DenseNet169', 'DenseNet201', 'DenseNet264'] def Co...
# # Copyright (c) 2021 IBM Corp. # 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 writi...
import cv2 from sklearn.externals import joblib from .image_preprocessing import get_features from ..config import config def predict_sum(image_path): print('Read image...') img = cv2.imread(image_path) print('Image read. Loading classifier...') clf = joblib.load(config['CLASSIFIER']['TrainedModelPath...
from __future__ import print_function import numpy as np import theano import theano.tensor as T import lasagne import ctc num_classes = 5 mbsz = 1 min_len = 12 max_len = 12 n_hidden = 100 grad_clip = 100 input_lens = T.ivector('input_lens') output = T.ivector('output') output_lens = T.ivector('output_lens') l_in ...
# Copyright 2022 The FastEstimator 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 appl...
"""Serializer of the operations details""" # DRF from rest_framework import serializers from rest_framework.validators import UniqueValidator # Models from root.Acme.models import Category, Product, OrderRequest, OperationDetail from root.users.models import User, Profile class OperationsModelSerializer(serializers...
# trim_prot_alignments.py # This script is to trim the protein aligned exons for all samples based on the ref exon in ORF. # The input will be the EXON_NAME_AA.fasta and the output will be a EXON_NAME_AA_trimmed.fasta file with their # trimmed protein alignments # This script can be executed by running $ python trim_pr...
import os.path as osp from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class IGNDataset(CustomDataset): """IGN dataset. In segmentation map annotation for IGN, 0 represents zones without information so ``reduce_zero_label`` is fixed to True. The ``img_suffi...
# -*- coding: utf-8 -*- from java.sql import Connection from com.ziclix.python.sql import zxJDBC from datetime import datetime from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.base.features import BaseDatabaseFeatures from django.db.backends.base.operations import BaseDatabaseOper...
def chkAcid(acid): acidLegals = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' if len(acid) == 8: for ch in acid: if ch not in acidLegals: return False return True else: return False def chkJobid(jobID): randAlpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno...
""" Test the multi_sample_split module """ import numpy as np from numpy.testing import assert_almost_equal from hidimstat.multi_sample_split import aggregate_medians, aggregate_quantiles def test_aggregate_medians(): n_iter, n_features = 20, 5 list_sf = (1.0 / (np.arange(n_iter * n_features) + 1)) lis...
import numpy as np class Relu(object): def __call__(self, a): return np.maximum(0, a) def gradient(self, a): return np.heaviside(a, 0) class Tanh(object): def __call__(self,x): return np.tanh(x) def gradient(self, x): return 1.0 - np.tanh(x)**2 class Sigmoid(object):...
# -*- coding: utf-8 -*- # effort of writing python 2/3 compatiable code from __future__ import print_function from __future__ import division from __future__ import unicode_literals from future.utils import iteritems from operator import itemgetter, attrgetter, methodcaller import sys, time, argparse, csv import cPro...
import copy from .graph import Graph ''' 单源最短路 一次性得到单个点到全部点的最短路径 广度优先搜索 ''' class Dijkstra(Graph): def __init__(self, size=10, graph=None): super().__init__(size=size, graph=graph) self.result = copy.deepcopy(self.graph) def shortest_path(self, start=None, end=None): S = {start: 0...
__author__ = 'clarkmatthew' from prettytable import PrettyTable from colorama import Fore, init from subprocess import Popen, PIPE import re cmd_string = 'euca-describe-images --show-empty-fields -h' cmd = cmd_string.split() p = Popen(cmd, stdout=PIPE) p_out, p_err = p.communicate() if p.returncode: print str...
#coding:utf-8 import requests # 解析来自 高德 的数据,输出 地铁站和站点名称、经纬度等信息 ## 遍历搜索 ## 地图标注
''' original_3DRecGAN++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ''' from torchvision import datasets, transforms from base import BaseDataLoader import os import torch import pandas as pd from base import BaseDataLoader from base import DataPrefetcher import numpy as np import re import matplotlib...
import json from pymongo import MongoClient def save_to_json(custom_object): file = "../../output.json" try: with open(file) as f: data = json.load(f) data["tweets"].append(custom_object) f.close() with open(file, 'w') as f: json.dump(data, f, i...
# -*- coding: utf-8 -* import math import maya.api.OpenMaya as OpenMaya nodeName = 'mlEulerToExpmap' expmapName = ('expmap', 'em', u'Expmap') expmapElementName = (('expmapX', 'emx', 'Expmap X'), ('expmapY', 'emy', 'Expmap Y'), ('expmapZ', 'emz', 'Expmap Z')) rotateName = ('r...
#!/usr/bin/env python # # Prints a concise summary of a benchmark output as a TSV blob. # # Example usage: # # $ BenchmarkXXX_DEVICE > bench.out # $ benchSummary.py bench.out # # Options SortByType, SortByName, or SortByMean may be passed after the # filename to sort the output by the indicated quantity. If no sort opt...
import csv import io import librosa as lr import matplotlib.pyplot as plt import numpy as np plt.interactive(False) #data_saved ,Sales_precision, Customers_precision ayarlanmalı print('lets go') #import datasets keys = [] X = [] # feature vector array Y_Sales = [] # feature target array Y_Customers = [] # feature ...
import pandas as pd def dataframe_summary(df): """ :param df: dataframe :return: dataframe of: column name type of object number of distinct values unique values (showsa a maximum of 10 unique values) missing values """ print("Database has {:,} rows and {:,...
# -*- coding: UTF-8 -*- # Copyright 2016-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) ''' Causes one or several :xfile:`help_texts.py` files to be generated after each complete build of the doctree. See :doc:`/dev/help_texts` for a topic overview. Usage ===== In your :xfile:`conf.py` file, add ...
# 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, software # distribu...
# -*- coding: utf-8 -*- # # Copyright (c) 2013 Vincent Batoufflet. # # License: BSD, see LICENSE for more details. # from flask import Response, flash, redirect, render_template, request, session, url_for from flask.ext.babel import _ from plume import ATOM_LIMIT, FILE_PREFIX, HELP_PREFIX from plume.backend import * f...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import asyncio import logging from asyncio import StreamReader, StreamWriter from typing import AsyncGenerator, Optio...
"""Update-related models. .. moduleauthor:: Glen Larsen, glenl.glx at gmail.com """ from django.db import models from mutopia.models import Piece, Instrument class InstrumentMap(models.Model): """Normalize instruments by mapping names to specific instruments. We want users to specify known instruments in ...
import codecs class Node(object): """Node An Object storing Node Data Vars: id: 20-byte Array hash: 160-bit int Func: distance: Calculate Distance between two Nodes """ def __init__(self, id, remote=None): """Node Args: id: Node id, a by...
import logging import psycopg2 from psycopg2 import Warning as DBWarning, Error as DBError from gevent.lock import RLock from time import time from turbo_config import db_host, db_name, db_user, db_pass, db_max_age # Logger logger = logging.getLogger('sticks.db') class DBSession(object): _instance = None _co...
# -*- coding: utf-8 -*- import logging from puzzle.models.sql import Suspect logger = logging.getLogger(__name__) class SuspectActions(object): def add_suspect(self, case_obj, variant_obj): """Link a suspect to a case.""" new_suspect = Suspect(case=case_obj, variant_id=variant_obj.variant_id, ...
"""Module with utilities functions and constants for expression parsing.""" import re # Dictionary with all supported operations and their priorities. SUPPORTED_OPERATIONS = { "+": 1, "-": 1, "*": 2, "/": 2, "//": 2, "%": 2, "^": 3, "<": 4, "<=": 4, "==": 4, "!=": 4, ">=": 4, ">": 4 } # Regular express...
#!/usr/bin/env python3 import nltk import re import sys bo_file = open('citations.da-bo', 'w') da_file = open('citations.da', 'w') citationmatcher = r'\<([^\{]+)\{([^\}]+)\}\>' parenth_stripper = r'\(.+\)' parenth_only_stripper = r'[\(\)]' metachars_stripper = r'[#ʁɔː]' brackets_stripper = r'\[.+?\]' errors = 0 fo...
from http import HTTPStatus from flask_restplus import Resource, reqparse, abort from werkzeug.datastructures import FileStorage from app.api import file_storage from app.api.namespaces import aspects from app.authorization.permissions import EditAspectPermission from database import db from database.models import As...
# !/usr/bin/env python # coding=utf-8 # @Time : 2020/4/25 18:07 # @Author : yingyuankai@aliyun.com # @File : __init__.py from .bert_for_qa import BertForQA
# app.py import os import sys from flask import Flask sys.path.insert(0, os.path.dirname(__file__)) app = Flask(__name__) @app.route('/') def index(): return 'hi'
# -*- coding: utf-8 -*- """CLI Box.""" # system module from typing import TYPE_CHECKING from uuid import UUID # community module import click # project module from .utils import output_listing_columns, output_properties from ..models import MessageBox, MetaDataSession, Module, NoResultFound, Schema, generate_uuid i...
class LuciferMoringstar(object): DEFAULT_MSG = """👋Hello {mention}.....!!!\nIt's Power Full [{bot_name}](t.me/{bot_username}) Here 😎\nAdd Me To Your Group And Make Sure I'm an Admin There! \nAnd Enjoy My Pever Show.....!!!🤪""" HELP_MSG = """**<i><b><u> How To Use Me 🤔?</i></b></u> 💡 <i>First You Must Jo...
import os import logging import subprocess from time import sleep max_load_retry = 30 sleep_init = 0.2 sleep_backstep = 1.5 tmp_file_path = '' special_names_src = ['Seagate', 'system', 'windows', 'temp', 'tmp', 'ProgramData', '..', '.', 'home', "Documents and Settings", 'gam...
#!/usr/bin/env python from optparse import OptionParser import os import numpy as np import scipy as sp ################################################################################### # pie_tab.py # # For each motif, output a tab delimited file corresponding to the number of cds, # lncrna, pseudogene, 3' utrs, 5' ...
# Copyright 2020 Ray Cole # # 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...
""" Problem 4 (Hard) This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, t...
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
# Generated by Django 3.0.7 on 2020-06-26 11:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('album', '0004_auto_20200626_1356'), ] operations = [ migrations.RemoveField( model_name='photos', name='photo_image', ...
import datetime from django.core.mail import send_mail from rent.models import rentOrder from login.models import User def test(): orders = rentOrder.objects.filter(type='long') for order in orders: user = order.rent_paidUser send_mail('房租缴费提醒', "您的订单:" + str(order.id) + "本月房租未交,请前往缴费", '12056...
""" 03-complex-resonator.py - Filtering by mean of a complex multiplication. ComplexRes implements a resonator derived from a complex multiplication, which is very similar to a digital filter. It is used here to create a rhythmic chime with varying resonance. """ from pyo import * import random s = Server().boot() ...
import os from importlib.machinery import SourceFileLoader class Configuration(): def __init__(self, config_file, action): self.config_file = config_file # path + config file self.action = action def load(self): # load experiment config file config = SourceFileLoader('conf...
# Copyright 2017 Google 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 or agreed to in writing, ...
# flake8: noqa from .environment import EnvironmentWrapper from .gym import GymEnvWrapper from .atari import AtariEnvWrapper
import pandas as pd s = pd.Series(range(10)) print(s) # 0 0 # 1 1 # 2 2 # 3 3 # 4 4 # 5 5 # 6 6 # 7 7 # 8 8 # 9 9 # dtype: int64 print(s.rolling(3)) # Rolling [window=3,center=False,axis=0] print(type(s.rolling(3))) # <class 'pandas.core.window.rolling.Rolling'> print(s.rolling(3).sum...
# # PySNMP MIB module Application-Monitoring-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Application-Monitoring-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:33:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
# Python imports. import random from os import path import sys # Other imports. from HierarchyStateClass import HierarchyState from simple_rl.utils import make_mdp from simple_rl.planning.ValueIterationClass import ValueIteration parent_dir = path.dirname(path.dirname(path.abspath(__file__))) sys.path.append(parent_di...
""" (C) Copyright 2021 IBM Corp. 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, software d...
import logging from enum import unique, Enum logger = logging.getLogger(__name__) @unique class WirenControlType(Enum): """ Wirenboard controls types Based on https://github.com/wirenboard/homeui/blob/master/conventions.md """ # generic types switch = "switch" alarm = "alarm" pushbutt...
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
from hashlib import sha256 class BitCoinMinner: block_number: int transaction: str previous_hash: str prefix_zero: int max_nonce: int def __init__(self, block_number: int, transaction: str, previous_hash: str, prefix_zero: int, max_nonce: int = None): self.block_number = bl...