content
stringlengths
5
1.05M
# response status for client use # if value is tuple, the second value will be returned as the error message # database db_add_err = 'db_add_err', 'Database Add Error' db_delete_err = 'db_delete_err', 'Database Delete Error' db_update_err = 'db_update_err', 'Database Update Error' db_query_err = 'db_query_err',...
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Functions for adding results to perf dashboard.""" import calendar import datetime import httplib import json import os import ...
from binance.client import Client import pandas as pd from utils import configure_logging from multiprocessing import Process, freeze_support, Pool, cpu_count import os try: from credentials import API_KEY, API_SECRET except ImportError: API_KEY = API_SECRET = None exit("CAN'T RUN SCRIPT WITHOUT BINANCE AP...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @author: James Zhang # @data : 2021/3/15 from functools import wraps from selenium.common.exceptions import NoSuchElementException, \ TimeoutException, StaleElementReferenceException import allure from easy_automation.utils.custom_logging import Logs log = Logs(...
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = self.right = None def insert(nums: List[int]) -> TreeNode: root = TreeNode(nums[0]) for node in nums[1:]: insert_helper(root, node) return root def insert_helper(root: TreeNode, node: in...
from peewee import SqliteDatabase from . import db from .models import * def create_staff(forename, surname, username, password): Staff.create(forename, surname, username, password) def create_module(code, name, leaders, assessors=None): pass
""" Example UCT implementation in Python, which (with a Java wrapper) can be used to play in the Ludii general game system. The implementation is based on our Example UCT implementation in Java (see: https://github.com/Ludeme/LudiiExampleAI/blob/master/src/mcts/ExampleUCT.java) NOTE: because we don't extend the abstr...
from pandas import DataFrame, concat from pandas.core.apply import frame_apply from sklearn import linear_model from smart_fruit.feature_class import FeatureClassMeta from smart_fruit.model_selection import train_test_split from smart_fruit.utils import csv_open __all__ = ["Model"] class ModelMeta(type): def _...
from django.contrib import admin from django.contrib import admin from .models import Department from modeltranslation.admin import TranslationAdmin # Register your models here. @admin.register(Department) class DepartmentAdmin(TranslationAdmin): list_display = ("name", "short_description") prepopulated_fields ...
#coding: utf-8 __author__ = "Lário dos Santos Diniz" import requests import json class ApiConnection: def __init__(self, url = ""): self._url = 'http://127.0.0.1:8080/' if url != '': self._url = url def checks_cutting_work(self, job_id): try: r = requests.ge...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.ensemble import BaggingClassifier from sklearn.linear_model import LinearRegression from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import StandardScaler f...
# 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 ...
# -*- coding: utf-8 -*- # Line segmentation script for images with PAGE xml. # Derived from the `import_from_larex.py` script, parts of kraken and ocropy, # with additional tweaks e.g. pre rotation of text regions # # nashi project: # https://github.com/andbue/nashi # ocropy: # https://github.com/tmbdev/ocropy/ # ...
import phidgets_relay_class as relay import time print(f'Starting relay init ') brd_ser_nums = [439515, 449740, 449901, 439525] brd1 = relay.phidget_relay_class(brd_ser_nums[0]) brd2 = relay.phidget_relay_class(brd_ser_nums[1]) brd3 = relay.phidget_relay_class(brd_ser_nums[2]) brd4 = relay.phidget_relay_class(brd_ser_...
# Generated by Django 2.2.7 on 2019-12-02 12:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='...
# 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 # "License"); you may not u...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
# -*- coding: utf-8 -*- import json import os import random import sys sys.path.append('../') from config import base_dir data_dir = os.path.join(base_dir, 'data') src = 'jieba' target = 'fasttext' process_name = ['train', 'valid', 'test'] def function(): for name in process_name: content =open(os.pat...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Git grep wrapper for arguments re-ordering, that can use options after filenames # # Usage: git-gerp [<git-grep-argument>...] # # Copyright (c) 2018 htaketani <h.taketani@gmail.com> # This software is released under the MIT License. import sys import re import subprocess ...
from .getDepends import getDepends def importLib(): """Load python dependent libraries dynamically""" libList = getDepends() from pip._internal import main as pip_main import importlib def install(package): pip_main(['install', package]) createVar = locals() for lib in libList...
# Copyright 2013-2014 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and ...
from auth0_client.commands import administration, tickets, tenants, stats, jobs, guardian, emails, email_templates, blacklists, users_by_email, users, user_blocks, rules_config, rules, resource_servers, logs, client_grants,clients, connections, custom_domains, device_credentials, grants
"""Integration tests for Constellix""" from unittest import TestCase from lexicon.tests.providers.integration_tests import IntegrationTestsV2 # Constellix does not currently have a sandbox and they enforce domain # uniqueness across the service. You'll need your own production credentials # and a unique domain name...
# Collected error samples: # {'errorMessage': 'Pair(s) not found', 'event': 'subscriptionStatus', 'status': 'error'} # {'errorMessage': ['Unknown field.']} # => currently handled in subscription status schema
"""Top-level package for zillionare-backtest.""" __author__ = """Aaron Yang""" __email__ = "aaron_yang@jieyu.ai"
import iprofile import math import numpy as np import scipy.cluster.hierarchy as sch import navigate import matplotlib.pyplot as plt """ Reads file rms.matrix to fetch centroid RMSD and Similarity in I(Q) for all centroid pairs. Finally, compare RMSD and Similarity """ # Location of sassena files containing I(Q) sId =...
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python import os import django def get_all_subjects(): """ Get all subjects with more than one period and annonate with active_period_objects """ from devilry.apps.core.models import Subject subject_queryset = Subject.objects.all().prefetch_active_period_objects() return subj...
from torch.nn.parallel import DataParallel, DistributedDataParallel from rflib.utils import Registry MODULE_WRAPPERS = Registry('module wrapper') MODULE_WRAPPERS.register_module(module=DataParallel) MODULE_WRAPPERS.register_module(module=DistributedDataParallel)
""" Converting simple structured data from XML or JSON into authorityspoke objects. These functions will usually be called by functions from the io.loaders module after they import some data from a file. """ from typing import Any, NamedTuple from typing import Dict, List, Optional, Tuple, Sequence, Union from ancho...
from letra._helpers import _check_for_duplicate_templates from letra import Label from ..helpers import stub_labels from pytest import raises def test__check_for_duplicate_templates_raises_on_duplicates(): dup_label = Label(name="dup", description="oops", color="a24b2a") dup_first_copy = Label(name="dup", des...
# Generated by Django 2.2.10 on 2020-04-06 13:46 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import simple_history.models import uuid class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_...
def binary_search(arr, ele): first = 0 last = len(arr) - 1 found = False while first <= last and found == False: mid = (first + last) // 2 if arr[mid] == ele: found = True else: if arr[mid] > ele: last = mid - 1 else: ...
from django.forms import Form from rest_framework.response import Response from rest_framework.serializers import HyperlinkedModelSerializer from backend.models import Arena, Card def raise_error(message, status=500): return Response({'error': {'message': message}}, status=status) def refresh_error(message, st...
import sys import re import pandas as pd util_path = str ( sys.argv[1]) cpu_model_path = str ( sys.argv[2]) gpu_model_path = str ( sys.argv[3]) cpu_gpu_timeline_path = str ( sys.argv[4]) cpu_model = {} fp = open ( cpu_model_path, 'r') for line in fp: m = re.match ( '(\S+),(\S+)', line) if m != None: freq = int ( ...
from django.contrib import admin from .models import member # Register your models here. admin.site.index_title="DASHBOARD" admin.site.site_title="ADMIN" admin.site.site_header="Nidaghatta Family-ADMIN" class memberAdmin(admin.ModelAdmin): list_display = ('name',"image") list_filter = ('is_requested_to_delete...
from sys import stdin,stdout # stdin = open("/home/shiva/Learning/1.txt","r") # stdout = open("/home/shiva/Learning/2.txt","w") primelist = [2] append = primelist.append def mysieve(n): primes = [True] * (n); sqrtn = (int(n**.5)+1) | 1 for i in range(3,sqrtn,2): if primes[i]: append(i) primes[i*i::2*i] = [Fa...
import numpy from cupy import _core from cupy._core import _fusion_interface from cupy._core import fusion from cupy._sorting import search from cupy_backends.cuda.api import runtime def copyto(dst, src, casting='same_kind', where=None): """Copies values from one array to another with broadcasting. This fun...
# -*- coding: utf-8 -*- from mamaprofile.myprofile import profile
# coding: utf-8 # BlackSmith mark.2 # exp_name = "allweb" # /code.py v.x28 # Id: 26~27c # Code © (2011-2013) by WitcherGeralt [alkorgun@gmail.com] class expansion_temp(expansion): def __init__(self, name): expansion.__init__(self, name) UserAgents = UserAgents import htmlentitydefs, json UserAgent = ("Us...
from ._filter import Filter from ._registration._apply_transform import ApplyTransform from ._registration._learn_transform import LearnTransform from ._segmentation import Segmentation
from abc import ABC, abstractmethod, abstractproperty from functools import wraps from time import sleep import pyvisa def reject_nan(func): @wraps(func) def wrapped(*args, **kwargs): for _ in range(10): response = func(*args, **kwargs) if response == response: ...
import shutil from pathlib import Path from typing import IO import pytest from setup import _Package _INIT_CONTENT = ''' """Package stands for pytest plugin.""" __author__: str = 'Volodymyr Yahello' __email__: str = 'vyahello@gmail.com' __license__: str = 'MIT' __version__: str = '0.0.0' __package_name__: str = 'pyt...
# Time: O(m + n) # Space: O(1) class Solution(object): def mergeAlternately(self, word1, word2): """ :type word1: str :type word2: str :rtype: str """ result = [] i = 0 while i < len(word1) or i < len(word2): if i < len(word1): ...
from sys import stdin, stdout def coinFlip(I, N, Q): if N % 2 == 0: return N // 2 else: if I == 1: if Q == 1: return N // 2 else: return (N // 2) + 1 else: if Q == 1: return (N // 2) + 1 els...
import importlib import traceback info = { "name": "reload", "type": 1, "description": "Reloads a command", "id": "reload", "options": [ { "name": "command", "description": "Command name", "type": 3, "required": True }, { ...
class Solution: def numberOfArithmeticSlices(self, A): """ :type A: List[int] :rtype: int """ if len(A) < 3: return 0 left, right = 0,3 results = 0 while right <= len(A): sli = A[left:right] if sli[1] - sli[0] == sli...
import rebound import unittest import ctypes def getc(sim): c = [] for i in range(sim.N): c.append(sim.particles[0].x) c.append(sim.particles[0].y) c.append(sim.particles[0].z) c.append(sim.particles[0].vx) c.append(sim.particles[0].vy) c.append(sim.particles[0]...
# SPDX-FileCopyrightText: 2018 ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2018 Michael Schroeder (sommersoft) # # SPDX-License-Identifier: MIT # This is a library for the Adafruit Trellis w/HT16K33 # # Designed specifically to work with the Adafruit Trellis # ----> https://www.adafruit.com/products/1...
import argparse import os import sys import preprocessing.util as util import preprocessing.config as config import traceback def wikidump_to_new_format(): doc_cnt = 0 hyperlink2EntityId = util.EntityNameIdMap() hyperlink2EntityId.init_hyperlink2id() if args.debug: infilepath = config.base_fol...
#C1949699 # # import math import random import re import time from turtle import numinput from cv2 import INTER_AREA, INTER_BITS, INTER_CUBIC, INTER_LANCZOS4, INTER_LINEAR, INTER_LINEAR_EXACT, INTER_MAX, imread, imshow, waitKey import numpy as np import cv2 import os from multiprocessing import Process, Manager data_p...
""" This is a dedicated editor for specifying camera set rigs. It allows the artist to preset a multi-rig type. They can then use the create menus for quickly creating complicated rigs. """ class BaseUI: """ Each region of the editor UI is abstracted into a UI class that contains all of the widgets for t...
################################################################################ # file: settings.py # description: energydash settings ################################################################################ # Copyright 2013 Chris Linstid # # Licensed under the Apache License, Version 2.0 (the "License"...
import os import json import pandas as pd import numpy as np from matplotlib import pyplot as plt from segmenter.visualizers.BaseVisualizer import BaseVisualizer class BoostVisualizer(BaseVisualizer): def boxplot(self, clazz, results): results = results[["loss", "fold", "boost_fold"]] results = re...
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from os import link from itemadapter import ItemAdapter from selenium import webdr...
# *-* coding: utf-8 *-* import sys import os from email.mime.application import MIMEApplication from asn1crypto import cms, core from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.asymmetric import pa...
# Here is the list of modules we need to import # from . import authorizations from authorizations import at,at_url,headers_at,encoded_u,encoded_u_td,td_base_url,get_headers import atws import atws.monkeypatch.attributes import pandas as pd import requests def get_notes_for_list_of_note_ids(id_=[]): query_notes...
import os import gzip import cPickle import numpy as np from scipy.io import loadmat import pyhsmm_spiketrains.models reload(pyhsmm_spiketrains.models) from pyhsmm_spiketrains.internals.utils import split_train_test def load_synth_data(T, K, N, T_test=1000, model='hdp-hmm', v...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 claviering <claviering@sunn> # # Distributed under terms of the WTFPL license. from sys import stdout for j in range(2,1001): k = [] n = -1 s = j for i in range(1,j): if j % i == 0: n += 1 ...
import mock import unittest2 import urllib import urllib2 from mlabns.util import constants from mlabns.util import message from mlabns.util import prometheus_status class ParseSliverToolStatusTest(unittest2.TestCase): def test_parse_sliver_tool_status_returns_successfully_parsed_tuple(self): status = {...
# Copyright 2015 NEC Corporation. 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 ...
import time import os # for organization, encode parameters in dir name def setOutDir(params): timestamp = str(int(time.time())) try: jobid = os.environ['SLURM_JOBID'] except: jobid = 'NOID' if params['root'] is None: root = os.path.join(os.environ['HOME'], "STM", "experiments"...
# -*- coding: utf-8 -*- import os, sys, pdb import argparse import torch from torch.utils import data import torchvision.transforms as standard_transforms import numpy as np FILE_PATH = os.path.abspath(__file__) PRJ_PATH = os.path.dirname(os.path.dirname(FILE_PATH)) sys.path.append(PRJ_PATH) from yolo_v2.proj_utils....
# # cogs/messages.py # # mawabot - Maware's selfbot # Copyright (c) 2017 Ma-wa-re, Ammon Smith # # mawabot is available free of charge under the terms of the MIT # License. You are free to redistribute and/or modify it under those # terms. It is distributed in the hopes that it will be useful, but # WITHOUT ANY WARRANT...
#Crie um programa que tenha uma funcao chamada voto() que vai receber como parametro o ano de nascimento #de uma pessoa, retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL ou OBRIGATORIO nas #eleicoes. #minha resposta def voto(ano): from datetime import date atual = date.today().year...
def octal_to_string(octal): result = "" value_letters = [(4,"r"),(2,"w"),(1,"x")] for octet in [int(n) for n in str(octal)]: b = format(octet, '03b') for n,v in enumerate(b): if (int(v) > 0): result += value_letters[n][-1] else: result ...
# -*- coding: utf-8 -* from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import argparse import numpy as np import random from time import sleep sys.path.append(os.path.join(os.path.dirname(__file__), 'common')) from common import face_im...
import requests import lxml.html as lh import pandas as pd url = 'https://www.bphc.org/onlinenewsroom/Blog/Lists/Posts/Post.aspx?List=24ee0d58%2D2a85%2D4a4a%2D855b%2Df5af9d781627&ID=1282&RootFolder=%2Fonlinenewsroom%2FBlog%2FLists%2FPosts&Source=https%3A%2F%2Fwww%2Ebphc%2Eorg%2FPages%2Fdefault%2Easpx&Web=03126e14%2D49...
from pathlib import Path import json from commiter.src.backend.tasks import Task1, AbstractTask from typing import * import pandas as pd class Backend: def __init__(self, path: Path, tasks_parsers: Sequence[AbstractTask]): self.path = path self.tasks_parsers = tasks_parsers if not self.pat...
import os import math import re from collections import OrderedDict import numpy as np import sys FWD_ALGO_list=[ "CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM", "CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM", "CUDNN_CONVOLUTION_FWD_ALGO_GEMM", "CUDNN_CONVOLUTION_FWD_ALGO_DIRECT", "CUDNN_CONVOLUTION_FWD_ALGO_FFT", "CU...
from .datagroup import DataGroup __all__ = ["DataGroup"]
# -*- coding: utf-8 -*- """ Created on Thu Sep 23 08:06:31 2021 @author: bcamc """ #%% Import Packages import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import InsetPosition, inset_axes from matplotlib.lines import Line2D import pandas as pd import numpy ...
"""Invoice views""" # Django REST Framework from rest_framework import mixins, viewsets, status from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated # Serializers from bugal.invoices.serializers import InvoiceModelSeri...
# Copyright 2004-2008 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) """ This file contains indexing suite v2 code """ file_name = "indexing_suite/element_proxy_traits.hpp" code = """// Copyrigh...
""" __name__ = model.py __author__ = Yash Patel __description__ = Defines model to be trained on the Cartpole data, predicting the directioal action to take given 4D observation state """ from keras.models import Sequential from keras.layers import Dense, Dropout def create_model(): model = Sequential() mod...
import sqlite3 class Database: """ DB connection and methods """ base_recipe_query = 'SELECT * FROM RECIPE' def __init__(self, connection_str): self.connection_str = connection_str def connect(self): self.connection = sqlite3.connect(self.connection_str) return self.connection def disconnect(self): ...
# CORES NO TERMINAL print("\033[1;30m---------SISTEMA ANSI DE CORES---------\033[m") print(" ") print("Código de abertura: Código de fechamento:") print("\033[1;30m\ 0 3 3 [0;30;40m + STRING + \ 0 3 3 [m\033[m") print(" ") print("Preenchimento do código de abertura:") print("\033[1;30m\ 0 3 3 [ ESTILO ; C...
#!/usr/bin/python3 import ctypes import os,sys,copy,math this_path = os.path.dirname(os.path.realpath(__file__)) assert(0==os.system('cd "%s" && make default' % this_path)) fds_lib = None libnames = ['fds_x86_64.so','fds_x86.so'] while libnames: so = libnames.pop() try: fds_lib = ctypes.CDLL(os.pat...
def align_tokens(tokens, text): point, spans = 0, [] for token in tokens: start = text.find(token, point) if start < 0: raise ValueError(f'substring "{token}" not found in "{text}"') end = start + len(token) spans.append((start, end)) point = end return ...
import os import sqlite3 from flask import Flask, render_template, g, request from flask_bootstrap import Bootstrap from flask_nav import Nav from flask_nav.elements import Navbar, View from forms import DangersForm, DiceRollForm, TravelForm from functions import fetch_animals_and_monsters, dice_roll import odatasfun...
import sys sys.path.append('..') import torch from model.encoder import swin_transformer,simplenet,trans_plus_conv,resnet def build_encoder(arch='resnet18', weights=None, **kwargs): arch = arch.lower() if arch.startswith('resnet'): backbone = resnet.__dict__[arch](**kwargs) elif arc...
#!/usr/bin/env python import json import yaml import urllib import os import sys from jsonref import JsonRef # type: ignore import click from openapi2jsonschema.log import info, debug, error from openapi2jsonschema.util import ( additional_properties, replace_int_or_string, allow_null_optional_fields, ...
import os.path import numpy from scipy.spatial import Delaunay import meshio from meshplex import MeshTri def simple0(): # # 3___________2 # |\_ 2 _/| # | \_ _/ | # | 3 \4/ 1 | # | _/ \_ | # | _/ \_ | # |/ 0 \| # 0-----------1 # X = numpy.a...
#!/usr/bin/env python3 import sys, os, unittest, logging, tempfile # Extend PYTHONPATH with local 'lib' folder jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir)) sys.path.insert(0, jasyroot) import jasy.core.Project as Project class Tests(unittest.TestCase): ...
# -*- coding: utf-8 -*- ''' myword ''' #from snsapi.plugin.renren import RenrenAPI from snsapi.snspocket import SNSPocket import json import sys import urllib2 import hashlib import time REPLY_GAP = 10 # seconds, 10 seems the minimum NEWS_QUERY_COUNT = 5 MY_NAME = "hsama2012" def can_reply(status): """ A fi...
from .base import Filth from .. import exceptions class CredentialFilth(Filth): type = 'credential' # specify how the username/password are replaced username_placeholder = 'USERNAME' password_placeholder = 'PASSWORD' @property def placeholder(self): ubeg, uend = self.match.span('user...
import tkinter widget = tkinter.Label(None, text='Hello GUI world!') widget.pack() widget.mainloop()
"""Helpful fixtures for testing with pytest and PostgreSQL. Use these fixtures to test code that requires access to a PostgreSQL database. """ import pathlib from typing import Callable, Generator, Union import psycopg2 import psycopg2.extensions import psycopg2.sql import pytest import testing.postgresql import lat...
# coding=utf-8 # 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 ...
import random import itertools import csv from typing import List, Union, Optional, NamedTuple # Configuration SIMULATE_ROUNDS = 1000 MATCH_SIZE = 4 MAX_RESHUFFLES = 10 # Data types class Card(NamedTuple): suit: str rank: Union[str, int] Hand = List[Card] class Player: @property def number(self...
import datetime from arend.settings import base from arend.queue.task import QueueTask class ProgressUpdater: def __init__( self, queue_task: QueueTask, suppress_exception: bool = True, verbose: bool = 1 ): self.queue_task = queue_task self.verbose = verbose ...
from django.contrib import admin # Register your models here. from .models import OrderModel, WoodFormModel, SkinFormModel, PaperFormModel admin.site.register(OrderModel) admin.site.register(WoodFormModel) admin.site.register(SkinFormModel) admin.site.register(PaperFormModel)
import numpy as np import matplotlib.pyplot as plt from skimage import measure regions = np.zeros((100,200,5)) print(regions.shape) regions[10:30,10:30,0] = 1 regions[10:30,40:70,0] = 2 regions[50:80,80:140,0] = 3 regions[85:100,100:150,0] = 4 regions[15:40,150:180,0] = 5 regions[10:30,10:70,1] = 1 regions[50:80,...
from .Cilindro import Cilindro from . import BinWriter as bin import os class Indice: def __init__(self, pkey, ruta): self.indx = [None]*30 self.intervalo = 30 self.pkey = pkey self.ruta = ruta self.readI() def readI(self): if os.path.exists(self.ruta+"/indx.b")...
############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SO...
import PikaStdLib import machine time = machine.Time() pwm = machine.PWM() pwm.setPin('PA8') pwm.setFrequency(2000) pwm.setDuty(0.5) pwm.enable() mem = PikaStdLib.MemChecker() while True: mem.now() time.sleep_ms(500) pwm.setDuty(0.5) time.sleep_ms(500) pwm.setDuty(0.001)
from django.conf import settings from django.views.static import serve urlpatterns = [ url(r'^Object_Detection/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), ]
#------------------------------------------------------------------------------- # Name: Logistic Regression # Purpose: # # Author: Nonlining # # Created: 17/04/2017 # Copyright: (c) Nonlining 2017 # Licence: <your licence> #-------------------------------------------------------------------------...
# -*- coding: utf-8 -*- from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured def ret_contenttypes(*args, **kwargs): """ Takes a blacklist or a whitelist of model names and returns queryset of ContentTypes """ if not 'app_label' in kwarg...
def funcTwo(): print("can you add stuff?")