content stringlengths 5 1.05M |
|---|
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Martin Paces <martin.paces@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2011 EOX IT Services GmbH
#
# Permission is here... |
"""
This app is for management of roles and permissions.
The permissions module only gives module instance operations
Instead of permissions let me introduce roles
INVENTORY ROLES
- Add Supplier
- View Supplier
- Delete Supplier
- Update Supplier
"""
# TODO: Look at examples of online generated re... |
from django.db.models.query_utils import Q
from product.models import Category, Gallery, Product, Review
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from product.serializers import CategorySerializer, CreateProductSerializer... |
"""Functions for selecting lists of timeslots based on certain criteria."""
import datetime
import functools
import itertools
import sqlalchemy
import lass.schedule.models
import lass.credits.query
import lass.common.time
import lass.schedule.filler
def process(slots, start, finish):
"""Processes a raw list of... |
#!/usr/bin/env python3
"""
Geoscience Australia - Python Geodesy Package
Transform Module
Ref1
http://www.icsm.gov.au/sites/default/files/GDA2020TechnicalManualV1.1.1.pdf
Ref2
http://www.mygeodesy.id.au/documents/Karney-Krueger%20equations.pdf
"""
import datetime
from math import radians
import numpy as np
from geo... |
from django import forms
from django.forms.models import modelformset_factory
import happyforms
from quieter_formset.formset import BaseModelFormSet
from tower import ugettext as _, ugettext_lazy as _lazy
import mkt
from mkt.reviewers.models import ReviewerScore, RereviewQueue
from mkt.webapps.models import Webapp
fr... |
from nltk.corpus import wordnet as wn
import sys
import os
import re
reload(sys)
sys.setdefaultencoding('UTF8')
pathstump = "/Users/Torri/Documents/Grad stuff/Thesis stuff/Data - Novels/Analysis/"
target = 'tagged'
specialwords = open("/Users/Torri/Documents/Grad stuff/Thesis stuff/Data - Novels/Analysis/no... |
from hikyuu import PG_FixedHoldDays
# 部件作者
author = "fasiondog"
# 版本
version = '20200825'
def part(days=5):
return PG_FixedHoldDays(days)
part.__doc__ = PG_FixedHoldDays.__doc__
if __name__ == '__main__':
print(part()) |
#!/usr/bin/env python3
import webbrowser
import argparse
def make_it_short():
parser = argparse.ArgumentParser(description='Tool for going to your most wanted links with short keys')
parser.add_argument('-w', metavar='url', dest='wanted', type=str,
help="""the wanted url ,
... |
import numpy as np
import pandas as pd
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot, offline
from datetime import datetime
today = datetime.today().strftime('%Y-%m-%d')
date_time = datetime.today().strftime('%Y-%m-%d-%H-%M')
import vis_layout
from manip... |
import os
Schedule = []
# # =================================== CLASSIFIER ========================================
# # ================== TRAINING AND TESTING ========================
# # Source: AMAZON_RO
# Schedule.append("python Main_Train_Test.py --s_dataset AMAZON_RO --mod... |
import numpy as np
import networkx as nx
import os
import pandas as pd
MAX_NODES = 3
NON_CLOSED_MAX_NODES = 4
DIRECTED_NX_GRAPH = './knowledge_graphs/Directed_KG_triples_no-mesh.gpickle'
NON_CLOSED_DIRECTED_NX_GRAPH = './knowledge_graphs/non-closed_Directed_KG_triples_no-mesh.gpickle'
#NON_CLOSED_DIRECTED_NX_GRAPH = "... |
from distutils.core import setup
setup(name = "id3reader",
version = "1.53.20070415",
description = "Python module that reads ID3 metadata tags in MP3 files",
author = "Ned Batchelder, Nik Reiman",
packages = ['id3reader'],
package_data = {'id3reader': ["id3reader/*"]}
)
|
from bot_box.features import requests, bsp, os # imported in __init__.py
''' Sample Response
<forismatic>
<quote>
<quoteText>Don't miss all the beautiful colors of the rainbow looking for that pot of gold.</quoteText>
<quoteAuthor></quoteAuthor>
<senderName></sende... |
# @Time : 2020/6/26
# @Author : Shanlei Mu
# @Email : slmu@ruc.edu.cn
# UPDATE:
# @Time : 2020/8/7
# @Author : Shanlei Mu
# @Email : slmu@ruc.edu.cn
"""
recbole.model.loss
#######################
Common Loss in recommender system
"""
import torch
import torch.nn as nn
class BPRLoss(nn.Module):
""" BPRLos... |
import json
import Stations.models as models
#from django.db.models import Avg
from datetime import datetime, timedelta
def sensorData2HighchartsData(data_rec, converter=None):
datastr = ''
for record in data_rec:
#highcharts uses unix timestamp in milliseconds
ts = record.timestamp.timestamp... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from socket import *
class POP3():
def connect(self,mailserver):
self.clientSocket = socket(AF_INET, SOCK_STREAM)
self.mailserver=mailserver
self.clientSocket.connect((self.mailserver, 110))
self.connect_recv = self.clientSocket.recv(1024).decode()
print(self.connect... |
# ==================================================================================
#
# Copyright (c) 2021 Samsung Electronics Co., Ltd. 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 obta... |
from eth2spec.test.context import spec_state_test, with_all_phases
from eth2spec.test.helpers.state import next_epoch_via_block
from eth2spec.test.helpers.attestations import next_epoch_with_attestations
def check_finality(spec,
state,
prev_state,
current_justi... |
from setuptools import setup
__version__ = "0.9.0"
__url__ = "https://github.com/carlskeide/is-healthy"
setup(
name="is-healthy",
version=__version__,
description="Mini healthcheck CLI",
author="Carl Skeide",
author_email="carl@skeide.se",
license="MIT",
keywords=[
"healthcheck",
... |
import logging
from typing import List, Optional
from overrides import overrides
import torch
from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler
logger = logging.getLogger(__name__)
@LearningRateScheduler.register("slanted_triangular")
class SlantedTriangular(Lear... |
# -*- coding: utf-8 -*-
"""
"""
import os
from datetime import datetime
from typing import Union, Optional, Any, List, NoReturn
from numbers import Real
import numpy as np
np.set_printoptions(precision=5, suppress=True)
import pandas as pd
from ..utils.common import (
ArrayLike,
get_record_list_recursive,
)
f... |
import hashlib
import json
import sys
import pytest
from asv.machine import Machine, MachineCollection
from write_asv_machine import floor_nearest, write_machine_info
@pytest.mark.parametrize("ram, expected_ram", [("98765", "98700"), ("", "")])
def test_write_asv_machine(mocker, ram, expected_ram):
mocker.patch... |
COPY_GOOGLE_DOC_KEY = '1BmhlbCaQnH3UkLt7nOy7hgGQ0QngvgOka3Jl92ZaPjY'
DEPLOY_SLUG = 'brazil'
NUM_SLIDES_AFTER_CONTENT = 1
# Configuration
AUDIO = False
VIDEO = False
FILMSTRIP = False
PROGRESS_BAR = True
|
# il faudrait charger les images aussi
# probleme avec les sauts a la ligne + mise en page ppt
from lxml import etree
from itertools import groupby
from win32com import client
def dataCut(datapath):
word = client.Dispatch("Word.Application")
word.Visible = False
doc = word.Documents.Open(datapath)
st... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
# ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers:
# Guowei Yang <471184555@qq.com>
# Wenyang Zhou <576825820@qq.com>
# Meng-Hao Guo <guomenghao1997@gmail.com>
# Dun Liang <randonlang@gmail.com>.
#
#
# This file is subject... |
from __future__ import print_function, unicode_literals
import os
import tempfile
import codecs
from bs4 import BeautifulSoup
from glob import glob
from libraries.general_tools.file_utils import read_file
from libraries.resource_container.ResourceContainer import RC
from libraries.app.app import App
class ProjectPrin... |
from .test_simple import EtcdIntegrationTest
from aio_etcd import auth
import aio_etcd as etcd
from . import helpers
import asyncio
from pytest import raises
class TestEtcdAuthBase(EtcdIntegrationTest):
cl_size = 1
def setUp(self):
# Sets up the root user, toggles auth
loop = asyncio.get_even... |
# -*- coding: utf-8 -*-
# File: base.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
from abc import ABCMeta, abstractmethod
import signal
import re
import weakref
import six
from six.moves import range
import tqdm
import tensorflow as tf
from .config import TrainConfig
from ..utils import logger, get_tqdm_kwargs
from ..... |
#!/usr/bin/python3
"""
DOWNLOAD ALL THE PROBLEMS OF CODE FORCE
"""
CODEF_SET_URLS = list()
CODEF_SET_URLS.append("https://codeforces.com/problemset")
CODEF_SET_URLS.append("https://codeforces.com/problemset/acmsguru")
print("Code Forces Scrapping.")
|
# -*- coding: utf-8 -*-
'''
Sync encryption normalization
'''
|
# Generated by Django 3.1.1 on 2020-09-29 20:01
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("carbon_quiz", "0047_auto_20200929_0849"),
]
operations = [
migrations.RemoveField(
model_n... |
"""
Runtime: 859 ms, faster than 34.17% of Python3 online submissions for Maximal Square.
Memory Usage: 16.5 MB, less than 69.25% of Python3 online submissions for Maximal Square.
"""
from typing import List
from typing import Optional
from copy import deepcopy
class Solution:
def maximalSquare(self, matrix: List[... |
#!/usr/bin/env python
import sys
def main(number):
result = 0
for i in range(1, number):
if i % 3 == 0 or i % 5 == 0:
result += i
return result
if __name__ == '__main__':
print(main(int(sys.argv[1])))
|
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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 use, copy, modify,... |
from math import atan2, sqrt, degrees, radians, cos, sin
from random import randint
class Vector2D:
#region INIT
def _get_xy(self, args):
"""Generates a x and y from any input
Returns:
[tuple]: x, y
"""
number_of_args = len(args)
if number_of... |
# -*- coding: utf-8 -*-
"""
Created on 17-03-2019 at 02:42 PM
@author: Vivek
"""
# The for-else loop to return the first even number or a '-1' if an even number is not found
def findEven(listOfNums):
for number in listOfNums:
if number % 2 == 0:
return(number)
else:
return -1
if _... |
from flask_restplus import fields
from app import app_api
BaseError = app_api.model('BaseError', {
'status': fields.String(required=True, description='Status'),
'statusCode': fields.String(required=True, description='Status code')
})
|
# This is a sample Python script.
import os
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import selenium.common.exceptions
import sys
from selenium import webdriver
import webbrowser
from seleni... |
import os
import unittest
import numpy as np
import pytest
from tests.fixtures.algorithms import DeviatingFromMedian
from timeeval.adapters import MultivarAdapter
from timeeval.adapters.multivar import AggregationMethod
class TestMultivarAdapter(unittest.TestCase):
def setUp(self) -> None:
np.random.see... |
# python standard library
import unittest
# the tuna
from tuna.commands.iperf.sumparser import SumParser
test_output = """
------------------------------------------------------------
Client connecting to 192.168.103.17, TCP port 5001
TCP window size: 22.9 KByte (default)
-------------------------------------------... |
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy.item import Item, Field
class ExampleItem(Item):
examplefield = Field()
|
'''Copyright 2018 Province of British Columbia
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,... |
if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
_winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
pass
class X:
def get_help_text(self):
return ngettext(
"Your password must contain at least %(min_length)d character.",
"Your password must c... |
while condition1:
pass
test1()
if condition:
pass
else:
test2() |
import unittest
import datetime
import os
from pickled_database.database import PickledDatabase
class TestPickledDatabaseA(unittest.TestCase):
def setUp(self):
self.file = 'test_db.pkl'
self.db = PickledDatabase(self.file)
self.db.clear_database()
def tearDown(self) -> None:
... |
import os
import sys
import subprocess
from logfetch_base import log
from termcolor import colored
def cat_files(args, all_logs):
log('\n', args, False)
if all_logs:
all_logs.sort()
for filename in all_logs:
log('=> ' + colored(filename, 'cyan') + '\n', args, False)
if f... |
"""Packaging settings."""
from codecs import open
from os.path import abspath, dirname, join
from subprocess import call
from setuptools import Command, find_packages, setup
import motey
this_dir = abspath(dirname(__file__))
with open(join(this_dir, 'README.rst'), encoding='utf-8') as file:
long_description =... |
import abc
import services.gesture.GestureValidatorService as gesture
import services.people.PeopleFilterService as people
import services.person.PersonValidatorService as person
import numpy as np
class InputProcessor:
def __init__(self):
self.gestureValidatorService=gesture.GestureValida... |
'''
Created on May 3, 2013
@author: Jonas Zaddach <zaddach@eurecom.fr>
'''
class Breakpoint():
"""This is an interface for breakpoints that are created by Debuggable.set_breakpoint"""
def __init__(self):
self._handler = None
def wait(self):
"""Wait until this breakpoint is hit"""
... |
import numpy as np
from numpy import exp, sqrt, power, cos, sin, pi
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class WaveFunction:
def __init__(self, method='rk2'):
self.method = method # Numerical method solutions: rk2
self.m, self.hbar, self.k0... |
import subprocess
import os
import shutil
import bigdataUtilities as util
import sys
if __name__ == "__main__":
# base directory in HDFS. Make sure you're able to write/delete in this directory
base_dir = "/analytics/leaf-compression"
version = "-0.1-SNAPSHOT"
# Comma seperated list of zookeeper nod... |
import fileinput
import re
# ROW, COL = (int(x) for x in re.findall(r'\d+', fileinput.input()[0]))
ROW, COL = 3010, 3019
def next_code(c):
return (c * 252533) % 33554393
def code_no(row, col):
# s = 1
# for x in range(row + col - 1):
# s += x
# return s + col - 1
return (((row + col - ... |
from font.Font import Font
from parser.OptionParserBuilder import OptionParserBuilder
import platform
from logger.Logger import Logger
from net.url import Uri
from net.process import FontDownloader
logger = Logger()
class EntryPoint:
@staticmethod
def main():
# 옵션 파서 생성
args = OptionParserBu... |
from app import db
from typing import List
from .model import Log
class LogService:
@staticmethod
def get_all() -> List[Log]:
return Log.query.all()
@staticmethod
def get_by_id(id: int) -> Log:
return Log.query.get(id)
@staticmethod
def update(id: int, body) -> Log:
m... |
# import the necessary packages
import face_recognition
import numpy as np
import argparse
import cv2
def alignFace(image, face_locations, face_landmarks):
'''
Let's find and angle of the face. First calculate
the center of left and right eye by using eye landmarks.
'''
leftEyePts = face_landmarks['left_eye']
r... |
import pathlib
import numpy as np
from Bio import SeqIO
import pandas as pd
import random
from skorch.dataset import Dataset
from .helper import Helper
from tqdm import tqdm
class TFBSDataset(Dataset):
seqs_start: int = 200
seqs_length: int
y_type: np.dtype = np.int64
dataframe: pd.DataFrame
helper... |
# -*- coding: utf-8 -*-
# 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
import logging
import json
import time
from ScrapyFrame.utils.base import EndsPipeline
from ScrapyFrame.utils.base import dat... |
for i in range(10):
print('Привет', i)
# [перегрузка функции range()]
# Напишем программу, которая выводит те числа
# из промежутка [100;999], которые оканчиваются на 7.
for i in range(100, 1000): # перебираем числа от 100 до 999
if i % 10 == 7: # используем остаток от деления на 10, для получения последней ... |
import unittest
class Solution:
@staticmethod
def findNthDigit(n: int) -> int:
"""
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Examp... |
import nodepy.runge_kutta_method as rk
import nodepy.convergence as cv
from nodepy import ivp
import matplotlib.pyplot as pl
pl.switch_backend('agg')
#Load some methods:
rk4=rk.loadRKM('RK44')
SSP2=rk.loadRKM('SSP22')
SSP104=rk.loadRKM('SSP104')
#Define an IVP:
#myivp=ivp.exp_fun(1.)
myivp=ivp.load_ivp('test')
#Start... |
from django.apps import AppConfig
class MathematicsConfig(AppConfig):
name = 'modules.mathematics'
|
class Library:
def __init__(self, list_of_books, library_name):
# creating a blank dictionary
self.lend_data = {}
self.list_of_books = list_of_books
self.library_name = library_name
# add book to dictionary
for books in self.list_of_books:
self.lend_data[... |
'''
Created on May 14, 2020
This file is subject to the terms and conditions defined in the
file 'LICENSE.txt', which is part of this source code package.
@author: David Moss
'''
from intelligence.intelligence import Intelligence
# Variable name for tracking people
AMPLITUDE_USER_PROPERTIES_VARIABLE_NAME = "amplitu... |
from __future__ import annotations
from typing import Literal
from prettyqt import core, network
from prettyqt.qt import QtCore, QtNetwork
from prettyqt.utils import InvalidParamError, bidict, mappers
mod = QtNetwork.QAbstractSocket
BIND_MODE = bidict(
share_address=mod.BindFlag.ShareAddress,
dont_share_ad... |
#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
"""https://adventofcode.com/2018/day/1
--- Day 1: Chronal Calibration (part 1)---
After feeling like you've been falling for a few minutes, you look at the
device's tiny screen. "Error: Device must be calibrated before first use.
Frequency drift detected. Cannot mainta... |
"""System utility functions."""
import errno
import logging
import os
import shutil
import subprocess
import sys
from typing import Optional, Union
import sparv.core.paths as paths
log = logging.getLogger(__name__)
def kill_process(process):
"""Kill a process, and ignore the error if it is already dead."""
... |
# Recursive Solution
def keypad(num):
# Base case
if num <= 1:
return [""]
# If `num` is single digit, get the LIST having one element - the associated string
elif 1 < num <= 9:
return list(get_characters(num))
# Otherwise `num` >= 10. Find the unit's (last) digits of `num`
... |
"""
To run this example, you need to put a VOAuth token with "google" scope in
a file called "TOKEN".
"""
from pyenlone.tasks import Tasks
from pyenlone.v import V
with open("TOKEN") as token:
tk = token.read().strip()
T = Tasks(voauth=tk)
V = V(token=tk)
your_google_id = V.googledata()["gid"]
ops = []
f... |
"""Define the Cluster object and cluster window"""
from __future__ import division
from __future__ import print_function
__authors__ = ['Martin Spacek']
import sys
import time
import random
import numpy as np
from PyQt4 import QtCore, QtGui, QtOpenGL, uic
from PyQt4.QtCore import Qt
getSaveFileName = QtGui.QFileDia... |
while True:
if something.changed:
do.stuff() # trailing comment
# Comment belongs to the `if` block.
# This one belongs to the `while` block.
# Should this one, too? I guess so.
# This one is properly standalone now.
for i in range(100):
# first we do this
if i % 33 == 0:
... |
class Config():
def __init__(self):
self.api_token = None
self.module_name = None
self.port = None
self.enable_2fa = None
self.creds = None
self.seen = set()
self.verbose = False
|
"""
Code generation and import tests.
"""
from hamcrest import (
assert_that,
calling,
equal_to,
is_,
raises,
)
from jsonschematypes.modules import ModuleLoader
from jsonschematypes.registry import Registry
from jsonschematypes.tests.fixtures import schema_for
def test_package_names():
"""
... |
from django.contrib import admin
from .models import Fcuser
# Register your models here.
class FcuserAdmin(admin.ModelAdmin):
list_display = ('email',)
admin.site.register(Fcuser, FcuserAdmin)
|
'''
实验名称:有源蜂鸣器
版本:v1.0
日期:2023.3
作者:01Studio
说明:让有源蜂鸣器发出滴滴响声
社区:www.01studio.org
'''
from gpiozero import Buzzer
import time
#引脚16,底电平发出响声
beep = Buzzer(16,active_high=False)
while True:
#循环发出响声
beep.on()
time.sleep(1)
beep.off()
time.sleep(1)
|
"""
Implement optics algorithms for optical phase tomography using GPU
Michael Chen mchen0405@berkeley.edu
David Ren david.ren@berkeley.edu
October 22, 2018
"""
import numpy as np
import arrayfire as af
import contexttimer
from opticaltomography import settings
from opticaltomography.opticsmodel import MultiTr... |
import csv
import json
colNames = ['Title','Price','Stock','Rating']
dataSet = [
['Rip it Up and ...', 35.02, 'In stock', 5],
['Our Band Could Be ...', 57.25, 'In stock', 4],
['How Music Works', 37.32, 'In stock', 2],
['Love Is a Mix ...', 18.03, 'Out of stock',1],
['Please Kill Me: The ...', 31.19... |
from Utils.Serializable import Serializable
from dataclasses import dataclass
from enum import Enum
class RecognitionOutcome(Enum):
NOT_RECOGNIZED = 1
RECOGNIZED = 2
UNCERTAIN = 3
UNKNOWN = 4
@dataclass
class RecognitionResponse(Serializable):
recognized_class: str
probability: float
out... |
import seaborn as sns
from matplotlib import pyplot as plt
from PyPDF2 import PdfFileMerger, PdfFileReader
import os
import shutil
import math
import warnings
warnings.filterwarnings('ignore')
def MakePlots(df, cat_features, con_features):
mergedObject = PdfFileMerger()
if os.path.exists('Plots'... |
from __future__ import annotations
import typing
import networkx
def depth_first_search(graph: networkx.DiGraph, root: typing.Any, explored: list, stack: list) -> None:
if root not in explored:
explored.append(root)
for vertex in graph.neighbors(root):
depth_first_search(graph, vertex,... |
#!/usr/bin/env python
# Copyright 2021 The PDFium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
def AddDirToPathIfNeeded(*path_parts):
# pylint: disable=no-value-for-parameter
path = os.path.abspath(os.path... |
#i know my code is shit you dont need to remind me
state = None
|
import os, datetime
# Class-based application configuration
class ConfigClass(object):
""" Flask application config """
#DO NOT use "DEBUG = True" in production environments
DEBUG = False
# Flask settings
SECRET_KEY = 'bestspangeopfjieaorhjfoiawoicewafoajpoewfjpoaewjfoewjf'
# Flask-SQLAlchemy... |
# Copyright 2020 Ville Vestman
# This file is licensed under the MIT license (see LICENSE.txt).
import os
import importlib
import torch
from asvtorch.src.settings.settings import Settings
import asvtorch.src.misc.fileutils as fileutils
def load_network(epoch: int, device):
model_filepath = os.path.join(fileutil... |
#!/usr/bin/python3
import os
import subprocess
import sys
import time
import boto3
from ruamel.yaml import YAML
AWS_REGIONS = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-3',
'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ca-central-1',
... |
# -*- coding: utf-8 -*-
__author__ = 'André Roberge'
__email__ = 'andre.roberge@gmail.com'
__version__ = '0.9.2'
from .easygui_qt import *
from .easygui_qt import __all__
|
from django.db import models
class Roles(object):
WHITE = "white"
BLACK = "black"
ROLE_CHOICES = [
(value, value) for attr, value in sorted(Roles.__dict__.items()) if not attr.startswith("_")
]
class Player(models.Model):
nickname = models.CharField(max_length=50)
role = models.CharField(max_len... |
# -*- coding: utf-8 -*-
"""Functions for grouping BEL graphs into sub-graphs."""
from . import annotations, provenance
from .annotations import *
from .provenance import *
__all__ = (
annotations.__all__ +
provenance.__all__
)
|
__all__ = []
try:
from featuretools.wrappers import DFSTransformer
__all__.append('DFSTransformer')
except ImportError:
pass
|
from PIL import Image, ImageFilter
img = Image.open('./images/yumi.png')
print(img)
print(img.mode)
print(img.size)
print(img.format)
#! Blur
filtered_img = img.filter(ImageFilter.BLUR)
filtered_img.save('./images/converted/yumi_blur.png', 'png')
#! Smooth
filtered_img2 = img.filter(ImageFilter.SMOOTH)
filtered_img... |
'''
Give the following parameters:
cityscapesPath: default is './data/CityDatabase'
classnames: specify which class you want to segment with instance
*IMPORTANT* if you change this, you have to modify label.py
and regenerate '*_gt*_instanceTrainIds.png' gt files.
MAX_instances: speci... |
import numpy as np
import numba
import numba.cuda as cuda
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array, check_random_state
from sklearn.utils.validation import _check_sample_weight
from scipy.sparse import issparse, csr_matrix, coo_matrix
from enstop.utils import (
... |
from builtins import getattr
import os
from warnings import warn, showwarning
try:
from numpy.linalg import inv, pinv, cond, solve
from scipy.stats import pearsonr
from sympy import symbols
from sympy.utilities.lambdify import lambdify
from sympy.parsing.sympy_parser import parse_expr
import ma... |
from typing import List
from google.api_core.exceptions import NotFound, GoogleAPICallError
from google.cloud.pubsub import PublisherClient, SubscriberClient
from testframework.exceptions.pubsub_checker_error import PubsubCheckerError
class PubsubChecker:
def __init__(self, project_id, publisher_client: Publis... |
from pytest_bdd import scenarios, then, when, parsers
from ui_automation_tests.pages.shared import Shared
from ui_automation_tests.pages.application_page import ApplicationPage
scenarios("../features/withdraw_and_surrender_application.feature", strict_gherkin=False)
RADIO_BUTTONS = "[type='radio']"
@when("I click ... |
"""
PyAudio-Play_example_01.py
Example to show how to use Play for PyAudio
Reference:
PyAudio, https://people.csail.mit.edu/hubert/pyaudio/
"""
# TODO: This didn't work at first. So do it again.
import pyaudio
import wave
import sys
from os import path
# Prepare the file
#filename = "jackhammer.wav"... |
import MudCommand
import MudConst
class cmdCredits(MudCommand.MudCommand):
def __init__(self):
MudCommand.MudCommand.__init__(self)
self.info['cmdName'] = "credits"
self.info['helpText'] = '''Displays the MUD credits'''
self.info['useExample'] = '''credits'''
def p... |
##-*****************************************************************************
##
## Copyright (c) 2009-2011,
## Sony Pictures Imageworks, Inc. and
## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
##
## All rights reserved.
##
## Redistribution and use in source and binary forms, with... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.