content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
# from contextlib import ContextDecorator
import pytest
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, Permission
from django.contrib.contenttypes.models import ContentType
from anonymous_permissi... |
def handle_none(default_val=None):
def decorator(func):
def wrapper(*args, **kwargs):
if args[0] is None:
return default_val
return func(*args, **kwargs)
return wrapper
return decorator
@handle_none()
def to_str(value, field, row, serializer_instance)... |
#!/usr/bin/env python
#
# overlaydisplaywidgets.py - Contents of the OverlayDisplayPanel.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module is used by the :class:`.OverlayDisplayPanel`. It contains
definitions of all the settings that are displayed on the
``OverlayDisplayPanel`` for each overlay type... |
from .base import Expression
__all__ = [
'CheckExpression',
'ComparableExpression',
'IndexedExpression',
'ObjectExpression',
'LogicalExpression',
'MathExpression',
'BitwiseExpression',
]
class CheckExpression(Expression):
"""
Overview:
Check expression.
Features:
... |
#!/usr/bin/env python3
def validate_user(username, minlen):
assert type(username) == str, "username must be a string" #
if minlen <1:
raise ValueError("minlen must be at least 1")
if len(username) < minlen:
return False #could be misleading if minlen is not proper. So
if not usernam... |
from django.db import models
from lego.apps.podcasts.permissions import PodcastPermissionHandler
from lego.utils.models import BasisModel
class Podcast(BasisModel):
source = models.CharField(max_length=500)
description = models.TextField()
authors = models.ManyToManyField("users.User", related_name="auth... |
#!/usr/bin/env python
# coding: utf-8
# http://www.pythonchallenge.com/pc/def/0.html
# print(2**38)
print(pow(2, 38)
# You will get 274877906944. The address of the next level is
# http: //www.pythonchallenge.com/pc/def/274877906944.html
|
from django.contrib import admin
from django.contrib.auth.models import Permission
# Register your models here.
from .models import classification
admin.site.register(Permission)
#admin.site.register(classification)
|
import pytest
import sciwing.constants as constants
from sciwing.datasets.seq_labeling.conll_dataset import CoNLLDatasetManager
from sciwing.utils.class_nursery import ClassNursery
import pathlib
PATHS = constants.PATHS
DATA_DIR = PATHS["DATA_DIR"]
DATA_DIR = pathlib.Path(DATA_DIR)
@pytest.fixture
def setup_science_... |
import sys
import json
import logging
from subprocess import run
from pathlib import Path
import pandas as pd
from dotenv import dotenv_values, find_dotenv
PROJECT_FOLDER = Path(__file__).resolve().parents[2]
LOG_FILE = PROJECT_FOLDER / "project.log"
logger = logging.getLogger(__name__)
ENV_VARS = dotenv_values(find... |
SURVEY_GET = {
'tags': ['설문지'],
'description': '설문지 리스트 불러오기(학생 학년에 따라 필터링됨)',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token',
'in': 'header',
'type': 'str',
'required': True
}
],
'responses': {
... |
# Copyright (C) 2011-2021, Manfred Moitzi
# License: MIT License
import pytest
import ezdxf
from ezdxf.entities.dxfgfx import DXFGraphic
from ezdxf.entities.dxfentity import DXFTagStorage
@pytest.fixture(scope='module')
def msp():
doc = ezdxf.new()
return doc.modelspace()
def test_delete_polyline3d(msp):
... |
#!/usr/bin/env python
# usage:
# $ fontbakery check-profile fontbakery.profiles.googlefonts -h
import argparse
import importlib.util
import os
import sys
from collections import OrderedDict
from fontbakery.checkrunner import (
distribute_generator
, CheckRunner
, ValueValidationEr... |
#! /usr/bin/python3
import argparse
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=
'Takes a raw unsigned 8-bit pcm on stdin and outputs a delta-encoded bitstream on stdout.')
input = sys.stdin.buffer
output = sys.stdout.buffer
pack = 0
last = ... |
#!/usr/bin/env python2.7
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--nepoch',type=int,default=50)
parser.add_argument('--version',type=str,default='4')
args = parser.parse_args()
import extra_vars
from subtlenet.models import singletons as train
train.NEPOCH = args.nepoch
tra... |
from __future__ import unicode_literals
from parglare import Grammar, Parser
from parglare.actions import pass_inner, pass_single
grammar = """
Calc: Assignments E;
Assignments: Assignment | Assignments Assignment | EMPTY;
Assignment: VariableName "=" Number;
E: E "+" E {left, 1}
| E "-" E {left, 1}
| E "*" E {left... |
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Krista'}
posts =[
{
'author': {'username': 'Shaun'},
'body': 'Beautiful Day in Denver'
},
{
'author': {'username': 'Devin'},
... |
# -*- coding: utf-8 -*-
# %reset -f
"""
@author: Hiromasa Kaneko
"""
import numpy as np
import pandas as pd
from dcekit.learning import DCEBaggingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_predict, train_test_spl... |
"""
Definition for KadaneResult
"""
class KadaneResult():
def __init__(self,maxSum,startIndex,endIndex):
self.maxSum = maxSum
self.startIndex = startIndex
self.endIndex = endIndex
"""
Definition for Rectangle
"""
class Rectangle():
def __init__(self,interiorResult,leftIndex,rightIndex,to... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
#!/usr/bin/env python3
"""Test generated Go code by running it."""
import argparse
import json
import os
import pathlib
import subprocess
from typing import Any, Sequence
import icontract
import temppathlib
import mapry
import mapry.go.generate
import mapry.go.generate.fromjsonable
import mapry.go.generate.parse
imp... |
from LiteBot import LiteBot
from utils import console
bot = LiteBot()
bot.system_commands()
bot.error_handler()
console.log("Initalizing Modules...")
bot.init_modules()
@bot.event
async def on_ready():
console.log(f"{bot.user.name} is online!")
bot.run(bot.token)
|
"""
Work in progress: This module contains functions to perform feature grouping
between multiple ms-runs/specfiles and the class Fgi and FgiContainer to
represent and store such groups.
"""
# Copyright 2015-2017 David M. Hollenstein, Jakob J. Hollenstein
#
# Licensed under the Apache License, Version 2.0 (the "Lice... |
import pytest
import numpy as np
from pyquaternion import Quaternion
from mockup import mock_luos_io
mock_luos_io()
from reachy.utils import rot # noqa: E402
from reachy.io.luos import SharedLuosIO # noqa: E402
from reachy.parts.motor import OrbitaActuator # noqa: E402
def test_orbita_goto():
luos_io = Sha... |
class CreditCardDefaults(object):
CountryOfIssuance = "USA"
IssuingBank = "NETWORK ONLY"
|
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from os.path import join
from tempfile import gettempdir
CONFIG_STATUS_OK = {
'reboot_signal_file': join(gettempdir(), 'reboot-required.freshly_minted'),
'created_at_file': join(gettempdir(), 'reboot-required.c... |
# Python 3 SDK for the KUSANAGI(tm) framework (http://kusanagi.io)
# Copyright (c) 2016-2021 KUSANAGI S.L. All rights reserved.
#
# Distributed under the MIT license.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
def test_actiondata_enti... |
import random
import string
import uuid
from core import output
def generate_token(size=32):
return ''.join(random.SystemRandom().choice(
string.ascii_lowercase + string.ascii_uppercase + string.digits
) for _ in range(size)
)
def store_creds(
module,
user,
password,
two_fact... |
b = _State(0)
import time
def run():
_print('tof test')
_goto('start')
for i in range(8):
# sleep(0.1)
_print('shuttin', i)
tof.start(i)
tof.stop(i)
# sleep(5)
# with _while(lambda: b.val < 10):
# z = tof.measure(7)
# @_do
# def _():
# r.forward(150 + 20 - z.val)
# return
_L('start')
r.speed... |
from rest_framework.pagination import PageNumberPagination
class RestrictedPagination(PageNumberPagination):
page_size = 10
max_page_size = 100
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import threading
import logging
import time
logging.basicConfig(level=logging.DEBUG,
format='[%(levelname)s] (%(threadName)-10s) %(message)s')
def worker(_id):
logging.debug("Worker: %d" % i)
time.sleep(1)
return
[threading.Thread(name="... |
# coding=utf-8
import random
from novel.swallows import (
Location, ProperLocation, Treasure, PluralTreasure,
Container, ProperContainer,
Item, Weapon, Horror
)
from novel.swallows import MaleCharacter, FemaleCharacter
# 世界:
# 更多反应的尸体:
# -如果他们同意,采取一对一的行动
# 协议后:
# 呼叫警察(他们有一个座机?这可能是娱乐性的。
# 如果他们共享两者之间的一个移动电... |
import os
from webrecorder.standalone.standalone import StandaloneRunner
# ============================================================================
class WebrecorderRunner(StandaloneRunner):
def __init__(self, argres):
super(WebrecorderRunner, self).__init__(warcs_dir=argres.warcs_dir,
... |
"""Provide some utilities for building simulation applications.
.. autofunction:: check_step
.. autofunction:: inviscid_sim_timestep
.. autoexception:: ExactSolutionMismatch
.. autofunction:: sim_checkpoint
.. autofunction:: create_parallel_grid
"""
__copyright__ = """
Copyright (C) 2020 University of Illinois Board ... |
import psycopg2
from psycopg2 import sql
_connection = None
def _get_connection():
global _connection
if _connection is None or _connection.closed != 0:
_connection = psycopg2.connect(dbname='test', user='testing', password='testing', host='localhost')
_connection.autocommit = True
return... |
# -*- coding:utf-8 -*-
from datetime import datetime
import urllib2
from flask import Blueprint, request, g, render_template, url_for, redirect, jsonify
from sqlalchemy import func
from bg_biz.orm.pay.charge import Charge
from bg_biz.orm.pay.transaction import Transaction
from bg_biz.orm.user import User
from bg_biz.pa... |
import numpy as np
import time
import multiprocessing
import copy
from functools import partial
from datetime import date
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
from math import log, sqrt
import sys
from regret_class import MOS... |
# -*- coding: utf-8 -*-
"""
meraki
This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ).
"""
class CombineOrganizationNetworksModel(object):
"""Implementation of the 'combineOrganizationNetworks' model.
TODO: type model description here.
Att... |
import numpy
import core
import sklearn.cluster
import deckstats
import random
def kmeans(cmdr, k=4):
# random.seed(52485)
cmdr = core.sanitize_cardname(cmdr)
card_to_idx = {}
idx_to_card = {}
dims = None
decks = []
i = 0
for deck in core.get_all_decks():
if deck['commander'... |
from __future__ import absolute_import
from django.conf import settings
from .models import RedditCredentials
import logging
from django.conf import settings
logger = logging.getLogger(__name__)
logging.config.dictConfig(settings.LOGGING)
class RedditMiddleware(object):
def process_request(self, request):
... |
#!/usr/bin/env python3
import csv
import os
import re
import logging
import numpy as np
from collections import Counter
from logging import debug, info, warning, basicConfig
basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
from scipy.stats import describe, zscore
score_names = "german english math la... |
# coding: utf-8
"""
Looker API 3.1 Reference
### Authorization The Looker API uses Looker **API3** credentials for authorization and access control. Looker admins can create API3 credentials on Looker's **Admin/Users** page. Pass API3 credentials to the **/login** endpoint to obtain a temporary access_token.... |
num=0
sum=0
while num<11:
sum=sum+num
num=num+1
print(sum)
num=0
sum=0
print('Enter num2')
num2= input()
while num<num2
sum=sum+num
num=num+1
print(sum)
|
import unittest
from tilecloud import Tile, TileCoord
class TestTile(unittest.TestCase):
def test_empty(self) -> None:
tile = Tile(TileCoord(0, 0, 0))
self.assertEqual(tile.content_type, None)
self.assertEqual(tile.content_encoding, None)
self.assertEqual(tile.data, None)
... |
import numpy as np
import pandas as pd
import nibabel as nib
import scipy.signal as signal
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def corr_volume(im, cv):
"""Compute the correlation between an f-MRI image and a convolution, voxel by voxel"""
ci = im - np.expand_dims(np.mean(im, 3), 3... |
"""
Structure learning for forced displacement.
"""
import os
import json
import pandas as pd
import numpy as np
from time import time
from pomegranate import BayesianNetwork
import networkx
import tempfile
import pickle
import argparse
import datetime
from itertools import product
import faulthandler
faulthandler.e... |
"""
@brief test log(time=2s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import fix_tkinter_issues_virtualenv, ExtTestCase
from pyensae.finance.astock import StockPrices
class TestStockGraphOHLC(ExtTestCase):
tick = 'MSFT'
source = 'yahoo_new'
de... |
import multiprocessing
from ctypes import c_bool
def generate_queue():
"""
Generates a proxy object of class :class:`~multiprocessing.Queue`
:rtype: multiprocessing.Queue
"""
m = multiprocessing.Manager()
return m.Queue()
def generate_flag():
"""
Generates a shared boolean value usin... |
import pytest
from ethtx_ce.backend.exceptions import Web3ConnectionException
from ethtx_ce.backend.providers.web3_provider import Web3Provider, connect_chain
class TestW3RepositoryForMainnet:
"""
WARNING!
Those are connection tests, they test connection to eth node and accessibility to different functio... |
import json
import os
import arrow
import pytest
from virt_backup.backups import DomBackup
from virt_backup.domains import get_xml_block_of_disk
from virt_backup.backups.snapshot import DomExtSnapshot
from virt_backup.exceptions import DiskNotFoundError, SnapshotNotStarted
from helper.virt_backup import MockSnapshot
... |
import os
import hydra
from omegaconf import DictConfig
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning import Trainer
from model.lightning import LightningDLReg
from model.utils import MyModelCheckpoint
import random
random.seed(7)
@hydra.main(config_path="conf", config_name="config"... |
import math
import operator
class Color_Class:
def rgb_to_hex(rgb):
return '%02x%02x%02x' % rgb
class Color_Analysis:
def Calculate_Mode_RGB(image, middle, borderdistance):
start = x,y = middle[0] - borderdistance, middle[1] - borderdistance
RGBDic = {}
for i in range(int(start[0]), int(start[0] + borderdi... |
import asyncio
loop = asyncio.get_event_loop()
|
from rest_framework import serializers
from post.models import Post
from author.models import Author
from comment.models import Comment
from django.forms.models import model_to_dict
# Post Serializer
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = (
... |
"""Socket API Configuration & Validation."""
# Standard Library
from pathlib import Path
# Third Party
from pydantic import FilePath, BaseModel
class Api(BaseModel):
"""Socket API Configuration Paramenters."""
port: int = 4801
path: FilePath = Path("/tmp/48ix_routingpolicy_api.sock")
|
from django.db import models
from django.contrib.auth.models import User
from easy_thumbnails.fields import ThumbnailerImageField
class Perfil(models.Model):
GENERO_CHOICES = (
('M', 'Masculino'),
('F', 'Femenino'),
('S', 'Sin especificar'),)
user = models.OneToOneField(User, on_delete... |
from django.test import SimpleTestCase
from cpu.random import Random
from game.transforms import Board
def sample_input():
return [
'x', 'x', ' ',
'o', ' ', ' ',
'o', ' ', 'x',
]
class RandomAiTest(SimpleTestCase):
def test_picks_random(self):
data = sample_input()
... |
import time
from functools import wraps
from urllib.parse import urlencode
from django import forms
from django.forms.utils import flatatt
from django.urls import reverse
from django.utils.encoding import force_str
from django.utils.html import escape, format_html
from django.utils.safestring import mark_safe
from dja... |
command = input().split()
products_list = []
while command[0] != "No":
if command[0] == "OutOfStock":
product = command.pop(1)
if product in products_list:
for index, value in enumerate(products_list):
if value == product:
products_list[index] = "None"... |
import boto3
import re
import datetime
import time
ec = boto3.client('ec2')
iam = boto3.client('iam')
"""
This function looks at *all* snapshots that have the tags "Type:Automated" and
"DeleteOn" containing the current day formatted as YYYY-MM-DD. The function will
delete the if the todays date is > than the "DeleteO... |
from models.v1 import Classifier as ClassifierV1
def build_classifier(name, data):
return ClassifierV1().build(name, data)
def load_classifier(name):
return ClassifierV1().load(name)
if __name__ == '__main__':
classifier = build_classifier('it-helpdesk-20210109', 'dataset/it-helpdesk-20210109.csv')
... |
#!/usr/bin/python
#
# 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
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, make_response, request, render_template, jsonify
from pyRRD_Redis import RRD_redis
import datetime
import csv
from io import BytesIO, StringIO
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure impor... |
try:
import importlib.resources as resources
except ImportError:
import importlib_resources as resources
with resources.open_text('torchray', 'VERSION') as f:
__version__ = f.readlines()[0].rstrip()
|
# -----------------------------------------------------------
# Test signature transform for tuples.
#
# (C) 2020 Kevin Schlegel, Oxford, United Kingdom
# Released under Apache License, Version 2.0
# email kevinschlegel@cantab.net
# -----------------------------------------------------------
import numpy as np
from ps... |
#! /usr/bin/env python
from setuptools import setup, find_packages
from codecs import open
from os import path
if __name__ == '__main__':
setup(
name='pySMOTE',
maintainer='Akaz',
version='1.0.0',
description='Python implementation of SMOTE',
license='MIT',
classifi... |
import os
import sys
import subprocess
import tempfile
import glob
import re
from vpnporthole.ip import IPv4Subnet
from vpnporthole.system.base import SystemCallsBase
class SystemCalls(SystemCallsBase):
__host_ip_cache = None
def __init__(self, *args, **kwargs):
super(SystemCalls, self).__init__(*ar... |
class VaultError(Exception):
def __init__(self, message=None, errors=None, method=None, url=None):
if errors:
message = ", ".join(errors)
self.errors = errors
self.method = method
self.url = url
super(VaultError, self).__init__(message)
def __str__(self):
... |
from flask_admin.contrib.sqla.view import ModelView
from flask_login import UserMixin
import datetime
from tentenblog import db, login_manager, admin
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
class User(UserMixin, db.Model):
__tablename__ = "users"
id = db.Column(db.I... |
#! /usr/bin/env python
"""
File: Particles.py
Copyright (c) 2016 Taylor Patti
License: MIT
This update on the Particles class confines the particles to a box
with a hole in it. The particles can leave the box or come back in if they
go through the hole in the box.
"""
import matplotlib
matplotlib.use('Agg')
import r... |
# coding: utf-8
"""
"""
import datetime
import typing
from .. import db
from .objects import Objects
from .users import User
class Location(db.Model):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False)
description = db.Column(db.Text... |
#!/usr/bin/env python3
"""Scapple to yWriter converter
Version @release
Requires Python 3.7 or above
Copyright (c) 2022 Peter Triesberger
For further information see https://github.com/peter88213/Scappex
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
import os
import... |
"""
The equilibrium module defines routines for interacting with
calculated phase equilibria.
"""
import pycalphad.variables as v
from pycalphad.eq.utils import point_sample, make_callable
from pycalphad.eq.utils import check_degenerate_phases
from pycalphad.constraints import sitefrac_cons, sitefrac_jac
from pycalpha... |
#================================
# RESEARCH GROUP PROJECT [RGP]
#================================
# This file is from pekaalto/sc2atari.
# Source: https://github.com/pekaalto/sc2atari
# Important: Note that the action space (ac_space) parameter is never used and effectively *ignored*!
import tensorflow as tf
from pys... |
from typing import Any, List
import pytest
from hypothesis import given, settings
from hypothesis import strategies as s
from hypothesis.strategies import SearchStrategy
from hpc.autoscale import hpctypes as ht
from hpc.autoscale.ccbindings.mock import MockClusterBinding
from hpc.autoscale.job.schedulernode import Sc... |
#!/usr/bin/env python
import signal
import time
import sys
import uuid
from rc522 import RFID
from lcd_i2c import *
import Adafruit_BBIO.GPIO as GPIO
# each card has 16 sectors 0 - 15
# sector 0 holds manufacturer data and may or may not be writable
# each sector is protected by two different keys, called A and B
# e... |
import os,sys
def read_term(infile):
'''
terminology format (line): ID<1>|ID<2>|...||term<1>|term<2>|...|term<n>
js format {ID<1>:{additionList:[ID<2>,...], termList:[term<1>,term<2>,...,<term<n>>]}}
'''
termList = open(infile,'r').read().strip().split('\n')
out_js = {}
for line in termList:
IDs, terms = line... |
import datetime
import bigflow
from bigflow.workflow import hourly_start_time
class HourlyJob(bigflow.Job):
id = 'hourly_job'
def execute(self, context):
print(f'I should process data with timestamps from: {context.runtime} '
f'to {context.runtime + datetime.timedelta(minutes=59, seconds... |
# models.py
# created by Sylvestre-Alvise Rebuffi [srebuffi@robots.ox.ac.uk]
# Copyright © The University of Oxford, 2017-2020
# This code is made available under the Apache v2.0 licence, see LICENSE.txt for details
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable... |
def test_get_variables():
class A:
def __init__(self, a: str):
self.a = a
def normal_f(self):
return f"normal a evaluates to {self.a}"
import inspect
# NOTE: getclosurevars has bugs that are still not fixed yet
# https://stackoverflow.com/questions/61964532/in... |
from flask import Flask,render_template,jsonify,request
from pymongo import MongoClient
import json
from Blueprints.UsuariosView import usuarios
from Models.Model import db
app = Flask(__name__)
app.register_blueprint(usuarios)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/chamado... |
"""
This module contains the GIF models.
"""
# Authors: Jean-Michel Begon <jm.begon@gmail.com>
# Licence: BSD 3 clause
from __future__ import division
import numbers
from abc import ABCMeta
from abc import abstractmethod
from math import ceil
import numpy as np
from scipy.sparse import issparse
from scipy.sparse i... |
documents = [
{"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
{"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
{"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
'1': ['2207 876234', '11-2'],
'2': ['10006'],
... |
from PIL import Image
def get_colors(pix_data, map_image):
colors = []
dictionary = {}
# type dictionary
for y in range(map_image.size[1]):
for x in range(map_image.size[0]):
if pix_data[x, y] != (0, 0, 0, 255):
color = pix_data[x, y]
if color not in colors:
colors.append(color)
dictionary[... |
#!/usr/bin/env python3
import argparse
from tkinter import Tk # Read clipboard contents
from urllib.parse import urlparse
from html import unescape
import requests
import re
#---------------------------------------------------------------------------------------------------
# Usage Notes & Examples (run with -h for f... |
class Solution:
def minSteps(self, s: str, t: str) -> int:
count = collections.Counter(s)
res = 0
for c in t:
if count[c] > 0:
count[c] -= 1
else:
res += 1
return res
class Solution:
def minSteps(self, s: str, t: str) -> in... |
# coding: utf-8
# Copyright 2018 www.privaz.io Valletech AB
#
# 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 l... |
# -*- coding: utf-8 -*-
from fastapi.encoders import jsonable_encoder
from starlette import status
from apps.places.models import Place
from apps.places.serializers.place import PlaceOutSerializer
from core.test.transaction_test_case import TransactionTestCase
class PlaceListTestCase(TransactionTestCase):
def s... |
#!/usr/bin/python
import roslib
roslib.load_manifest("moby")
import sys, socket, struct, rospy
from moby.msg import PWMCommand
ENABLE_FLAG = 0b10000000
if __name__ == '__main__':
rospy.init_node("navio_server")
port = rospy.get_param("~port", 5001)
timeout = rospy.get_param("~recv_timeout", 0.1)
... |
class Veiculo:
'''generica muitos genero'''
def __init__(self, cor, rodas, marca, tanque):
self.cor = cor
self.rodas = rodas
self.marca = marca
self.tanque = tanque
def abastecer(self, litros):
self.tanque += litros
|
import numpy as np
import cv2
import pyautogui
import matplotlib.pyplot as plt
#area_to_remove=np.array([[100,474],[100,375],[300,200],[520,200],[800,375],[800,475]]) # for driving segment
area_to_remove=np.array([[250,650],[450,500],[850,500],[1050,650]]) # for youtube video
def draw_lanes(image,lanes):
... |
"""Unit Test module for marvel api interface"""
from datetime import datetime
import json
import os
import unittest
import os.path as path
from marvelapiwrapper.entity import Entity
from marvelapiwrapper.authenticator import Authenticator
class TestEntities(unittest.TestCase):
def setUp(self):
test_path ... |
# Generated by Django 3.0.8 on 2020-08-12 12:31
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('boards', '0013_task_parent_task'),
]
operations = [
... |
from geneal.applications.template import TemplateChildClass
class TestTemplateChildClass:
def test_template_child_class(self):
tsp_solver = TemplateChildClass(n_genes=10)
tsp_solver.fitness_function("dummy_input")
tsp_solver.initialize_population("dummy_input", "dummy_input")
tsp... |
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/trips")
def trips():
return render_template("trips.html")
@app.route("/heartrate")
def heartrate():
return render_template("heartrate.html")
if __na... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 19:28:30 2018
@author: grcos
"""
import tkinter as tk
def winning():
print("You Win!")
def increment():
global count
if count.get() < 10:
count.set(count.get() + 1)
else:
winning()
root = tk.Tk()
count=tk.IntVar()
frame = tk.Frame(... |
from django import template
register = template.Library()
@register.filter(name = 'index')
def index(value, arg):
if len(value) <= arg:
return None
return value[arg]
|
# MIT License - Copyright Petri Laarne and contributors
# See the LICENSE.md file included in this source code package
"""A simplified version of the discrete data tutorial in the documentation."""
from __future__ import annotations
from ennemi import estimate_entropy, estimate_mi, pairwise_mi
import numpy as np
impo... |
import re
from typing import Union
from .constants import WHITE, BLACK, EMPTY
REGEX_MOVE_STRING = r'^([0-9]|1[0-8]) ([0-9]|1[0-8])$'
class Move():
__slots__ = ['position', 'color', 'previous_color', 'opposite_color',
'captures']
def __init__(self, color: int, position: Union[tuple[int], str],... |
from django.db import models
from django.contrib.auth.models import User
from resources.models import Topic, Resource
from django.core.urlresolvers import reverse
#TODO make a project model and add user projects field as foreign key
class Project(models.Model):
title = models.CharField(max_length=60)
descripti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.