content stringlengths 5 1.05M |
|---|
from .models import ProductModel, ProductCategory, CommentModel, Cart
from .serializers import (ProductSerializer, UserSerializer, CategorySerializer,
CommentSerializer, CartSerializer)
from rest_framework import generics
from django.contrib.auth.models import User
from rest_framework import p... |
# Copyright 2016 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at:
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
class UnsupportedRuntimeError(RuntimeError):
pass
class UnsupportedFormatError(ValueError):
pass
class UnsupportedArchError(ValueError):
pass
class UnsupportedOSError(ValueError):
pass
|
from django.contrib import admin
from placeholdr.models import Place, Trip, PlaceReview, TripReview, TripNode, RepRecord
from placeholdr.models import UserProfile
class PlaceAdmin(admin.ModelAdmin):
list_display = ('userId', 'lat', 'long', 'desc', 'name')
class TripAdmin(admin.ModelAdmin):
list_display = ('... |
import sys
sys.path.append("[/home/lucasquemelli/datapipeline/airflow/plugins]")
from datetime import datetime
from os.path import join
from airflow.models import DAG
from airflow.operators.alura import TwitterOperator
from airflow.contrib.operators.spark_submit_operator import SparkSubmitOperator
with DAG(dag_id="tw... |
print("\nArduboy Flashcart image builder v1.07 by Mr.Blinky Jun 2018 - Jun 2020\n")
# requires PILlow. Use 'python -m pip install pillow' to install
import sys
import time
import os
import csv
import math
try:
from PIL import Image
except:
print("The PILlow module is required but not installed!")
print("Use 'py... |
#!/usr/bin/env python3
# Copyright (c) 2022 Idiap Research Institute, http://www.idiap.ch/
# Written by Srikanth Madikeri <srikanth.madikeri@idiap.ch>
"""implementation of NG-SGD from Kaldi"""
from dataclasses import dataclass
from typing import Sequence
import torch
from math import exp
import logging
@torch.no_gr... |
import logging
from functools import update_wrapper
from django.contrib import admin
from django.db.models import Count, DateTimeField, Min, Max
from django.db.models.functions import Trunc
from .models import Provider, ProviderLog, ReadonlyProviderLog
logger = logging.getLogger(__name__)
# noinspection PyAttribut... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base")
from django.core.management import execute_from_command_line
current_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_pat... |
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
m = len(haystack)
n = len(needle)
if m < n:
return None
if m == n:
if haystack == needle:
return ne... |
# Importando as libraries
import csv
import rows
import datetime
import requests
import http.client
from pathlib import Path
from time import sleep
import settings
from collections import namedtuple
from divulga import checar_timelines, google_sshet
from autenticadores import google_api_auth
from gspr... |
# -*- coding: UTF-8 -*-
import argparse
import configparser
import os
CONFIG_FILE = 'sfpy.conf'
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)
parser = argparse.ArgumentParser()
parser.add_argument('--config-file', default=CONFIG_FILE,
type=argparse.FileType('r'))
args... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
from . import neuron
from . import axon
from . import dendrite
from . import spike
from . import synapse
from . import block
from . import classifier
from . import loss
from . import io
from . import auto
from . import utils
__all__ = [
... |
######################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# SPDX-License-Identifier: MIT-0 #
######################################################################
import os
import json
import numpy... |
#! /usr/bin/env python
''' ------------------------| Python SOURCE FILE |------------------------
The Description of this file.
@copyright: Copyright (c) by Kodiak Data, Inc. All rights reserved.
'''
import socket
import time
import os
import random
from kd.util.logger import getLogger
from kd.util.url import Url... |
"""
========================================================
Spatial Transformations (:mod:`scipy.spatial.transform`)
========================================================
.. currentmodule:: scipy.spatial.transform
This package implements various spatial transformations. For now,
only rotations are supported.
Rot... |
# exercise 5.2.6
from matplotlib.pylab import figure, plot, xlabel, ylabel, legend, ylim, show
import sklearn.linear_model as lm
# requires data from exercise 5.1.4
from ex5_1_5 import *
# Fit logistic regression model
model = lm.logistic.LogisticRegression()
model = model.fit(X,y)
# Classify wine as White/Red (0/1)... |
'''
Date: 2020-07-25 13:23:41
LastEditors: Jecosine
LastEditTime: 2020-08-22 02:18:40
'''
from mysql.connector import connect
class DBConnection:
def __init__(self):
self.con = None
self.cursor = None
self.init_database()
def init_database(self):
self.con = connect(user="root",... |
# -*- coding: utf-8 -*-
import os
import pytest
import ftplib
from pytest_sftpserver.sftp.server import SFTPServer
from pytest_localftpserver import plugin
from addons.ftp import utils
class TestSFTPList():
def test_sftp_list_root(self, sftpserver):
with sftpserver.serve_content({'foo_dir' : {}, 'bar.txt'... |
def search_grid(grid: list[list[str]], word: str) -> list[tuple[int, int]]:
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]
def check(i, j, idx, d):
if idx == len(word):
return True
else:
di = (i + d[0] * idx) % len(grid)
dj = (j ... |
import torch
from torch.nn import Linear, Module
from torch.nn.init import xavier_uniform_, constant_, xavier_normal_
from torch.nn.parameter import Parameter
from torch.nn import functional as F
class MultiheadAttention(Module):
r"""Allows the model to jointly attend to information
from different repr... |
"""MovieShow Model."""
from config.database import Model
class MovieShow(Model):
"""MovieShow Model."""
__table__ = 'movie_shows'
__casts__ = {'show_time': 'string', 'show_date': 'string'}
|
text = input("Enter something: ")
print(text)
print(type(text)) |
# Generated by Django 3.0.8 on 2020-09-02 05:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0009_auto_20200828_1240'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='image... |
#!/usr/bin/env python
#
# ********* Gen Write Example *********
#
#
# Available SCServo model on this example : All models using Protocol SCS
# This example is tested with a SCServo(STS/SMS/SCS), and an URT
# Be sure that SCServo(STS/SMS/SCS) properties are already set as %% ID : 1 / Baudnum : 6 (Baudrate : 10... |
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, \
ReplyKeyboardMarkup, CallbackQuery
from telegram.ext import Filters
import translations as tr
from translations import gettext as _
LIST_KEYBOARD = 'LIST_KEYBOARD'
LIST_KEYBOARD_INDEX = 'LIST_KEYBOARD_INDEX'
MAX_INLINE_CHARACTERS = 50
MAX_INLINE_... |
import os, sys, multiprocessing, hashlib, ast
from fractions import Fraction
from typing import Union, Callable
import numpy as np
from .kshell_exceptions import KshellDataStructureError
from .general_utilities import level_plot, level_density, gamma_strength_function_average
from .parameters import atomic_numbers
def... |
from django.contrib import admin
from .models import UserInteractionData
# Register your models here.
admin.site.register(UserInteractionData) |
# -*- coding: utf-8 -*-
"""Image model"""
from bson import DBRef
from flask import current_app
from flask_mongoengine import Document
from mongoengine import BooleanField, StringField, CASCADE
from .helpers import ReferenceField, DocumentMixin, URLField
from .user import User
class Image(DocumentMixin, Document):
... |
"""This module contains classes for analyzing error patterns in alignments
Its in pretty rough shape as its an early, but working, form. It works with alignqc. But it really needs some love to be a good module.
Error Analysis
I am to describe errors at several levels
Errors in the query sequence
1. Is a query ... |
import pytest
from constance import config
from django.contrib.auth.models import User
from django.core.files import File
import tram.models as db_models
from tram.ml import base
@pytest.fixture
def dummy_model():
return base.DummyModel()
@pytest.fixture
def user():
user = User.objects.create_superuser(use... |
from django.urls import include, path # importing module include and path
from . import views # importing views
from django.contrib import admin
urlpatterns = [
path('register', views.register, name='register'),
# path given to python to follow this route
path('login', views.login, name='login'),
... |
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/apply.ipynb (unless otherwise specified).
__all__ = ['preprocess_db_intra_image', 'aggregate_fold_stats']
# Cell
from ifcimglib import imglmdb, utils, preprocessing, cif2lmdb
import numpy
import matplotlib.pyplot as plt
from tqdm import trange
import pickle
import... |
import random
def FCFS(procesos):
tiempo=0
ejecucion = ''
t=[] #acumulador tiempo que toma el trabajo
e=[] #acumulador tiempo de espera
p=[] #acumulador T/t
for pro in procesos:
espera = tiempo - pro[0]
ejecucion += ''
if espera >= 0:
e.append(espera)
else:
tiempo = pro[0]
e.append(0)
for j in... |
import os, csv
from collections import defaultdict
from dotenv import load_dotenv
from pymongo import MongoClient
#from pymongo.server_api import ServerApi
# use with python3
#TODO - change data file from env variable to commandline parameter (required)
#TODO - make this an upsert so it updates existing ids if they e... |
# Generated by Django 3.2.9 on 2021-11-10 17:02
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('Shop', '0004_auto_20211110_1733'),
]
operations = [
migrations.AddField(
model_name='category',
... |
import http.server
import socketserver
from sys import version as python_version
from cgi import parse_header, parse_multipart
# https://stackoverflow.com/questions/4233218/python-how-do-i-get-key-value-pairs-from-the-basehttprequesthandler-http-post-h/13330449
if python_version.startswith('3'):
from urllib.parse i... |
"""Do some things"""
def add_two_numbers(first, second):
"""Adds together two numbers"""
return first + second
if __name__ == "__main__":
print(add_two_numbers(2, 5))
|
# DicomAligner.py by Francois Malan - 2011-06-23
# Revised as version 2.0 on 2011-07-07
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
from module_kits.misc_kit import misc_utils
import wx
import os
import vtk
import itk
import math
import numpy
class DICOMAligner(
NoConfigModule... |
import datetime
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import ListView
from projects.models import Project
from python_recipes import get_week_of_month_from_datetime, \
get_week_start_datetime_end_datetime_tuple
from tracking.models i... |
import io, sys, time
from datetime import datetime
sys.path.append('/home/pi')
from serial import Serial
import matplotlib.pyplot as plt
plt.ion()
ser = Serial('/dev/ttyS0', 9600, timeout=0.2)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), newline='\r')
x = []
y = []
while True:
try:
ser.flushInput()... |
import os
import torch
import torch.cuda.nvtx as nvtx
import torch.nn.functional as F
from torch import optim
from torch.nn.parallel import DistributedDataParallel as DDP
from model import DQN
class Agent():
def __init__(self, args, action_space):
self.action_space = action_space
self.n = args.multi_st... |
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='nginx-log-monitor',
version='0.0.1',
description='Nginx Log Monitor',
classifiers=[
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python ... |
# coding=utf-8
'''
@ Summary: 最终的效果是用脚本分离出1s和超过1s的,然后超过1s的手动进行剪辑,
音频文件名不改,在同一个音频文件夹路径下会生成两个音频文件夹,分别存放
超过1s和1s的音频
@ file: rm_aug_silence.py
@ version: 1.0.0
@ Update: 增加pathlib.Path() 这个库,可以无视平台差异
@ Version: 1.0.1
@ Author: Lebhoryi@gmail.com
@ Date: 2020/3/26 下午4:41
'''
from __future__ ... |
# Add parent to the search path so we can reference the modules(craft, pix2pix) here without throwing and exception
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import copy
import cv2
import numpy as np
from PIL import Image
from craft_text_detector import Craf... |
import decimal
import json
from datetime import date
from typing import Dict, List
from funds.models import Fund, Portfolio, Position
from funds.models import PortfolioSnapshot
from funds.services import prices
from funds.services.constants import CRYPTO_USD
# public
def get_market_value_on_date(portfolio, day: dat... |
from django.shortcuts import render
def index(request):
return render(request,'inicial/index.html')
|
# Copyright (c) 2019 PaddlePaddle 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 app... |
import math
from itertools import combinations
from itertools import product
from scipy.special import comb
import numpy
from collections import defaultdict
from consts import CLUSTERED_SUBSTITUTIONS_MIN_SIZE
from consts import WTS_MIN_PERCENT
def compress_snd_window(window):
n = len(window) // 2 + 1
win... |
import pickle
def atm():
file = "Account_details.pkl"
file_obj = open(file, "wb")
savings = int(50000)
pickle.dump(savings, file_obj)
user_choice = input("D: DEPOSIT "
"W: WITHDRAWAL "
"A: ACCOUNT DETAILS ")
file_obj = open(file, "rb")... |
from ftw import logchecker
import pytest
def test_logchecker():
with pytest.raises(TypeError) as excinfo:
checker = logchecker.LogChecker()
|
import random
import copy
from vertexInfo import VertexInfo
from edgeInfo import EdgeInfo
from topology.graph import GraphAsMatrix
class TopologyModel(object):
def __init__(self,G):
self._G = G
self._vertexInfoGen = VertexInfo
self._edgeInfoGen = EdgeInfo
def generateCl... |
"""
For reconfig V1
"""
import pandas
from collections import namedtuple
from typing import Tuple
from db_credentials import db_credentials
import mysql.connector
import datetime
import time
import paho.mqtt.publish as publish
from nr_funcs import float2arr
import json
RACK_ID = 1
UPDATE_RATE_S = 5
# relevant tag na... |
from classical_distinguisher import *
import time
# define cipher
CIPHER = "TEA"
# CIPHER = "XTEA"
# CIPHER = "RAIDEN"
if (CIPHER == "XTEA"):
# TODO
print(CIPHER)
if (CIPHER == "TEA"):
alpha = [0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x0000000F, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0xFFFFFFF1, 0x00000001, 0... |
import pytest
from yamlpath.merger.enums.outputdoctypes import (
OutputDocTypes)
class Test_merger_enums_outputdoctypes():
"""Tests for the OutputDocTypes enumeration."""
def test_get_names(self):
assert OutputDocTypes.get_names() == [
"AUTO",
"JSON",
"YAML",
]
def test_get_choices(self):
assert... |
import os
import sys
# Disable Tensorflow warning/info logs.
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
# Disable Tensorflow deprecation warnings
try:
from tensorflow.python.util import module_wrapper as deprecation
except ImportError:
from tensorflow.python.util import deprecation_wrapper as deprecation
deprecation... |
from flask import Flask
from flask_restx import Api
class Server():
def __init__(self):
self.app = Flask(__name__)
self.api = Api(self.app,
version='0.0.1',
title='flask api'
)
def run(self):
self.app.run(
debug=True
)
server = Server... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qtView.ui'
#
# Created: Tue Mar 10 18:45:33 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attribu... |
#! /usr/env/bin python3
import boto3
def lambda_handler(event, context):
users = {}
iam = boto3.client('iam')
for userlist in iam.list_users()['Users']:
userGroups = iam.list_groups_for_user(UserName=userlist['UserName'])
groups = list()
for groupName in userGroups['Groups']:
... |
from .imgloader_CT_clss_3D import pytorch_loader_clss3D
from .imgloader_CT_clss_3D_calcium import pytorch_loader_clss3D_calcium
|
import unittest
import time
from common import gpu_test
class TestJAX(unittest.TestCase):
def tanh(self, x):
import jax.numpy as np
y = np.exp(-2.0 * x)
return (1.0 - y) / (1.0 + y)
@gpu_test
def test_JAX(self):
# importing inside the gpu-only test because these packages... |
from sfml import sf
# python 2.* compatability
try: input = raw_input
except NameError: pass
def main():
# check that the device can capture audio
if not sf.SoundRecorder.is_available():
print("Sorry, audio capture is not supported by your system")
return
# choose the sample rate
samp... |
"""Tests for `declared_register` package."""
import pytest
from utils import formatters
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return requests.get('https://github.com/audreyr/cookiecutter-pypacka... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created: Aug 2017
@author: D34D9001@9R0GR4M13
"""
import kerri
import os
import subprocess
import symbo
import sys
import random
import requests
import webbrowser
from bs4 import BeautifulSoup as bs
from termcolor import colored
######################
# FAKE ... |
from timeflux.nodes.window import TimeWindow
import numpy as np
import pandas as pd
class Power(TimeWindow):
""" Average of squared samples on a moving window
Attributes:
i (Port): Default input, expects DataFrame.
o (Port): Default output, provides DataFrame and meta.
Args:
lengt... |
import py
import sys
class AppTestLocaleTrivia:
spaceconfig = dict(usemodules=['_locale', 'unicodedata'])
def setup_class(cls):
if sys.platform != 'win32':
cls.w_language_en = cls.space.wrap("C")
cls.w_language_utf8 = cls.space.wrap("en_US.utf8")
cls.w_language_pl ... |
import pkgutil
import sys, inspect
from typing import List
def list_modules_in_package(pkg_name) -> List[str]:
"""
:param pkg_name: imported package
:return: list of modules inside the package (modules will be loaded)
"""
modules = []
for importer, modname, ispkg in pkgutil.iter_modules(pkg_na... |
#!/usr/bin/env python3
# Copyright (c) 2021 CINN 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 r... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
list
'''
print("==========list=============")
students = ["jack", "tony", "john"]
students.append("kevin")
students.insert(1, "lisa")
students.pop()
students.pop(0)
print(students)
print(len(students))
print(students[0])
print(students[-1])
'''
tuple
'''
prin... |
from textwrap import dedent
from fjord.base.tests import TestCase
from fjord.mailinglist.tests import MailingListFactory
class TestMailingList(TestCase):
def test_recipients_empty(self):
ml = MailingListFactory(members=u'')
assert ml.recipient_list == []
def test_recipients_whitespace(self):... |
from __future__ import print_function
from PIL import Image
import PIL.ImageOps as po
import PIL.ImageDraw as pd
import PIL.ImageFont as pf
import PIL.ImageChops as pc
'''
f = Image.open("Inconsolata2.png")
w,h = f.size
sx = 0
sy = 0
dx = 72
dy = 58
nx = 10
ny = 29
fx = 28
fy = 16
fw = 16
fh = 32
imgw = 32
imgh = 1... |
# -*- coding: utf-8 -*-
"""
Main pysimu module
Created on Thu Aug 14 20:21:56 2014
/home/jmmauricio/Documents/private/pyWork11/PyPsat/src
@author: jmmauricio-m
"""
import numpy as np
from scipy.integrate import ode
class sim:
'''
Class to perform simuations
'''
def __i... |
from files.ListObject import functions, variableExist, functionExist
from files.Operations import add, subtract, multiply, divide
from files.FunctionsForSython import is_number, error
class Show():
def __init__(self):
self.nbParameters = 1
self.returnValue = False
def call(self, parameters... |
from collections import namedtuple
import csv
import os
import tweepy
from config import CONSUMER_KEY, CONSUMER_SECRET
from config import ACCESS_TOKEN, ACCESS_SECRET
DEST_DIR = 'data'
EXT = 'csv'
NUM_TWEETS = 100
Tweet = namedtuple('Tweet', 'id_str created_at text')
class UserTweets(object):
def __init__(sel... |
# -*- coding: utf-8 -*-
import pytest
from bravado_core.exception import SwaggerMappingError
from bravado_core.marshal import marshal_object
from bravado_core.spec import Spec
@pytest.fixture
def address_spec():
return {
'type': 'object',
'properties': {
'number': {
't... |
'''
Hamed Waezi
AI HW1
A*
Heuristic => Disjoint Patter database 4-4-4-3
'''
import heapq
import copy
import pickle as p
if __name__ == '__main__':
dim = int(input('Dimensions: '))
tiles = dim*dim
class Node: # Node is the state
def __init__(self, n, data, pp, blank, g):
self.n = n
s... |
from nltk.corpus import stopwords
from src.helpers.debug import top_keys
import re
stopwords = set(stopwords.words('english'))
stopwords.remove('don')
stopwords.remove('will')
# filter out token
def valid_tkn(tkn, valid_kw, invalid_kw):
tkn = tkn.lower()
if tkn in valid_kw:
return True
if tkn in i... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#老实说,目前还没搞懂这是在干啥呢
def addLayer(inputs,inputSize,outputsSize,activeFunction=None):
Weights=tf.Variable(tf.random_normal([inputSize,outputsSize]))
biases=tf.Variable(tf.zeros([1,outputsSize])+0.1)
Wxplusb=tf.matmul(inputs,Weig... |
from fenics import *
# Create mesh
mesh = UnitSquareMesh(30, 30)
# Create function space
Vele = VectorElement("Lagrange", triangle, 2)
Pele = FiniteElement("Lagrange", triangle, 1)
W = FunctionSpace(mesh, MixedElement([Vele, Pele]))
# Create boundary conditions
def noslip_boundary(x):
return near(x[1], 0.0) or ... |
import sys
inputString=""
numberOfDataToBeStored = 0
with open(sys.argv[1], 'r') as inputFile:
inputString = inputFile.read()
with open(sys.argv[2], 'w') as outputFile:
byTabNewline = inputString.split("\n")
for line in byTabNewline:
byComma = line.split(",")
characterName = byComma[5][3:... |
#!/usr/bin/env python3
import sys
import csv
from .. import utils
import numpy as np
from asmd.asmd import audioscoredataset
if len(sys.argv) < 1:
print("Error: missing algorithm, add `ewert` or `amt`")
sys.exit(2)
if sys.argv[1] == "ewert":
from .ewert.align import audio_to_score_alignment
FNAME = "r... |
import threading
from typing import List, Dict
import requests
class User:
def __init__(self, user_json: dict):
self.raw = user_json
self.id: int = user_json['id']
self.is_bot: bool = user_json['is_bot']
if 'last_name' in user_json:
self.name = f"{user_json['first_name... |
"""A python based DSL for InspectorTiger's testing."""
import argparse
import ast
import random
import string
import textwrap
from argparse import ArgumentParser
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum, auto
from itertools import chain
from pathlib import Path... |
import argparse
import json
import logging
import os.path
import time
from logging.handlers import RotatingFileHandler
from configparser import ConfigParser
from datetime import datetime
from datetime import date
from email.mime.text import MIMEText
import smtplib
from utils import log
from google.auth.transport.reque... |
import random
import json
stevilke = [1, 2, 3, 4, 5, 6, 7, 8, 9]
zacetek = 'Z'
class Plosca:
def __init__(self):
tabela = []
for _ in range(9):
vrstica = []
for _ in range(9):
vrstica.append(None)
tabela.append(vrstica)
... |
import sentencepiece as spm
import torch
class SMPEncoder:
def __init__(self, model_file):
self.model_file = model_file
self.sp = spm.SentencePieceProcessor(model_file=self.model_file)
def decode(self, tokens):
return self.sp.decode(tokens)
def encode(self, example):
code... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import datetime
import logging
from collections import defaultdict
from functools import lru_cache
from typing import (
Any, Callable, FrozenSet, Iterable, List, Mapping, MutableMapping,
NamedTuple, NewType, Optional, Seque... |
#Dependencies
import os
import shutil
#Main
def dir_files(dir_path):
try:
files = []
for ( root, _, filenames ) in os.walk(dir_path):
files.extend(filenames)
break
return None, files
except:
return "Unable to get directory files.", False
def recursive... |
from django.db import models
from smart_bookmarks.scrapers.db import ScrapePageTaskManager
class ScrapePageTask(models.Model):
id = models.AutoField(primary_key=True)
bookmark = models.OneToOneField(
"core.Bookmark", on_delete=models.CASCADE, related_name="_scrape_page_task"
)
created = model... |
from ctypes import alignment
import discord
from discord.commands import Option, slash_command
from discord.ext import commands
from discord.ext.commands.context import Context
guild_id_config = [CHANGEME]
static_file_locatin = 'CHANGEME'
class CRSDChart1H(commands.Cog):
def __init__(self, bot):
self.bot... |
from PyQt5.QtWidgets import QLabel, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QGroupBox, QPlainTextEdit
from PyQt5.QtCore import pyqtSignal, Qt
from sys import float_info as fli
import dataDisplay as dd
import numpy as np
class metaInfoWidget(QGroupBox):
#show_all = pyqtSignal()
#zoom_by_increment = pyqt... |
"""
OpenTMI client exceptions
"""
class OpentmiException(Exception):
"""
Default Opentmi Exception
"""
def __init__(self, message):
"""
Constructor
:param message:
"""
Exception.__init__(self, message)
self.message = message
class TransportException(Op... |
from collections import defaultdict
def num_occupied_adjacent_seats(grid, r, c):
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if not (i == 0 and j == 0):
count += int(grid[r + i, c + j] == "#")
return count
def iterate(grid):
new_grid = defaultdict(str... |
import typing
import sys
def main() -> typing.NoReturn:
s = list(input())
k = int(input())
n = len(s)
a = set()
a.add(tuple(s))
for _ in range(min(k, 1000)):
b = set()
for t in a:
t = list(t)
for i in range(n - 1):
t[i], t[i + 1] = t[i... |
"""
Copyright (c) 2021 Ricardo Baylon rbaylon@outlook.com
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCL... |
"""Embed a list of images in a PDF.
Images are placed top-centered.
"""
from typing import Sequence
from . import analyze, render
def convert(image_fnames: Sequence[str], pdf_name: str) -> None:
"""Converts the given image files into a PDF document.
Images are embedded as they are and not converted to e.g... |
"""
NAME
tarea_POO.py
VERSION
0.0.1
AUTHOR
Rodrigo Daniel Hernandez Barrera <<rodrigoh@lcg.unam.mx>>
DESCRIPTION
This is the example of a class to create characters in a video game,
use inheritance to create villains and heroes.
CATEGORY
Video game
GITHUB REPOSITORY
... |
"""Train Faster-RCNN end to end."""
import argparse
import os
# disable autotune
os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'
import logging
import time
import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet import gluon
from mxnet import autograd
from gluoncv.model_zoo import get_model
from gluoncv.... |
from distutils.core import setup
import py2exe
import glob
setup(name='Crystal Defense',
version='1.0',
author='Taylor Tamblin',
author_email='opethiantaylor@gmail.com',
py_modules=[ 'main', 'graphics', 'enemy', 'tower', 'towermenu',
'projectile', 'towerradius', 'easymap', 'tower_stats', 'buttons',... |
from humanmark.backends import available_backends
def test_backends():
"""Ensure plugin-registered backends are present and valid."""
backends = available_backends()
# Make sure our default backend is available at least.
assert 'markdown_it' in backends
# Ensure required fields are available on ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.