content stringlengths 5 1.05M |
|---|
import typing
import uuid
from datetime import datetime
class SetType:
_all: typing.Set = set()
def __init__(self, api_name: str, desc: str):
self.name = str(api_name)
self.desc = desc
SetType._all.add(self)
def __eq__(self, other):
if not isinstance(other, Se... |
# coding=utf8
import re
from decimal import Decimal
from typing import Union
MAX_VALUE_LIMIT = 1000000000000 # 10^12
LOWER_UNITS = '千百十亿千百十万千百十_'
LOWER_DIGITS = '零一二三四五六七八九'
UPPER_UNITS = '仟佰拾亿仟佰拾万仟佰拾_'
UPPER_DIGITS = '零壹贰叁肆伍陆柒捌玖'
class ChineseNumbers:
RULES = [
(r'一十', '十'),
(r'零[千百十]', '零... |
"""
Configuration module for ladim
"""
# ----------------------------------
# Bjørn Ådlandsvik <bjorn@imr.no>
# Institute of Marine Research
# 2017-01-17
# ----------------------------------
# import datetime
import logging
from typing import Dict, Any
import numpy as np
import yaml
import yaml.parser
from netCDF4 im... |
# TODO: put the name flexstring in the Class.
# Class is not "Named" and its names are not interned.
# Sym continues like today. Meth is named.
import os, re, sys
import collections
from logging import info
# Tuning.
MEMORY_LEN = 0x8000 # Somewhat arbtrary.
SYM_VEC_LEN = 256
CLASS_VEC_LEN = 256
# Leave a little ga... |
"""
This file contains the full ImageFeaturizer class, which allows users to upload
an image directory, a csv containing a list of image URLs, or a directory with a
csv containing names of images in the directory.
It featurizes the images using pretrained, decapitated InceptionV3 model, and
saves the featurized data t... |
#!/usr/bin/env python3
# Copyright (c) 2016 Anki, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
data = np.genfromtxt(path, delimiter=',', skip_header=1)
print(data, data.shape)
census = np.concatenate((... |
import sys
sys.path.append(r'F:\geostats')
from geostats import Scraping
from get_groupinfo import *
from get_eventsInfo import *
from urllib.error import HTTPError
import time,random,os
def generate_groupdf(groups):
groups_df = []
for j,group in enumerate(groups):
try:
record = get_groups... |
# Pulls in images from different sources
# Thomas Lloyd
import numpy as np
import flickrapi
import urllib.request
# make private
api_key = '55d426a59efdae8b630aaa3afbac4000'
api_secret = '72f4bde28a867f41'
keyword1 = 'toulouse'
def initialize(api_key, api_secret):
flickr = flickrapi.FlickrAPI(api_key, api_secre... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from sis_provisioner.management.commands import SISProvisionerCommand
from sis_provisioner.models.group import Group
class Command(SISProvisionerCommand):
help = "Prioritize groups for importing"
def handle(self, *args, *... |
from usuarios import Usuario
class Admin(Usuario):
def __init__(self, first_name, last_name, username, email):
super().__init__(first_name, last_name, username, email)
# self.priv = []
self.privileges = privileges()
# def show_privileges(self):
# print("\nPrivilegios:")
# ... |
import FWCore.ParameterSet.Config as cms
from RecoVertex.BeamSpotProducer.BeamSpot_cfi import *
|
# Copyright (c) 2015-2019 The Botogram Authors (see AUTHORS)
#
# 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, mod... |
#!/usr/bin/python
# Copyright 2022 Northern.tech AS
#
# 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 ap... |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sparse_ho.utils_plot import configure_plt, discrete_cmap
save_fig = True
# save_fig = False
configure_plt()
fontsize = 18
current_palette = sns.color_palette("colorblind")
algorithms = ['grid_search10', 'random', 'bayesian', 'grad_searc... |
# -*- coding: utf-8 -*-
from rest_framework.permissions import BasePermission
from v1.models.Board import Boards
from v1.models.Permissions import READ, WRITE, DELETE
class BoardPermission(BasePermission):
def has_object_permission(self, request, view, obj):
if view.action in ['get_states', 'retrieve']:... |
import socket
import struct
import time
import thread
from nc_config import *
NC_PORT = 8888
CLIENT_IP = "10.0.0.1"
SERVER_IP = "10.0.0.2"
CONTROLLER_IP = "10.0.0.3"
path_reply = "reply.txt"
len_key = 16
counter = 0
def counting():
last_counter = 0
while True:
print (counter - last_counter), counter... |
import logging
import numpy as np
import kubric as kb
from kubric.renderer.blender import Blender as KubricBlender
logging.basicConfig(level="INFO") # < CRITICAL, ERROR, WARNING, INFO, DEBUG
world_matrix = {
"bunny": np.array(
(
(-1.0, 3.2584136988589307e-07, 0.0, 0.7087775468826294),
... |
import pygame
def compare_surfaces(surf_a: pygame.Surface, surf_b: pygame.Surface):
if surf_a.get_size() != surf_b.get_size():
return False
for x in range(surf_a.get_size()[0]):
for y in range(surf_a.get_size()[1]):
if surf_a.get_at((x, y)) != surf_b.get_at((x, y)):
... |
from django import forms
from django.contrib import admin
from emoji_picker.widgets import EmojiPickerTextarea
from .attachment import DisplayImageWidgetStackedInline
class TranslationModelForm(forms.ModelForm):
text = forms.CharField(
required=True,
label="Text übersetzt",
help_text="Hi... |
#coding = utf-8
import os
import Config
from Function import Function
class File(object):
def __init__(self, srcFileName, isKeep = False, dstFileName = None):
self.srcFileName = srcFileName
self.isKeep = isKeep
self.dstFileName = dstFileName
self.testFuncs = []
self.codeLines = None
self.__readCode(... |
from django.db import models
from django.contrib.auth.models import AbstractUser
import uuid
# esta clase define el perfil de usuario y extiende de AbstractUser
# por que solo se necesitaba eliminar los campos de first_name y last_name
# el resto del contenido se podia conservar
class profile(AbstractUser):
"""Def... |
# -*- coding: utf-8 -*-
import subprocess
import pytest
# Use an empty temporary HOME and unset CASA_BASE_DIRECTORY (see
# conftest.py)
pytestmark = pytest.mark.usefixtures("isolate_from_home")
def test_help():
retval = subprocess.call(['casa_distro', '--help'])
assert retval == 0
def test_help_subcomma... |
import yaml
from typing import List, Union, List, Any, Dict, Tuple
import typing
import enum
import attr
import attrs_strict
from attrs_strict import type_validator
class MissingAttribute(Exception):
pass
def yaml_dump(d):
return yaml.dump(d, Dumper=yaml.Dumper)
def self_attributes(self, attrs):
retur... |
import requests
from requests.exceptions import HTTPError, ConnectionError
from .resources.functions import validate_protocol
class WordPressAPI:
""" WP API Object Definition """
def __init__(self, domain, username, password, protocol="https", namespace="wp-json"):
""" Object constructor """
... |
# The MIT License (MIT)
#
# Copyright 2020 Barbara Barros Carlos, Tommaso Sartor
#
# This file is part of crazyflie_nmpc.
#
# 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... |
#!/usr/bin/env python3
import sys
# read input file
with open(sys.argv[1], 'r') as fd:
partitions = fd.readlines()
# init
part1 = 0
part2 = 0
seat_ids = []
# part1
for partition in partitions:
# row
left = 128
row = 0
for letter in partition[:7]:
left = int(left / 2)
if letter ==... |
#!/usr/bin/env python
# coding: utf-8
import logging
def get_logger(obj, level=None):
logging.basicConfig()
logger = logging.getLogger(obj.__name__)
if level is not None:
logger.setLevel(level)
return logger
|
from django.test import TestCase
from .mixins import TwoUserMixin, ProposalMixin
from consensus_engine.models import ConsensusHistory
from django.utils import timezone
# models test
class ConsensusHistoryTest(TwoUserMixin, ProposalMixin, TestCase):
def test_snapshot(self):
p = self.create_proposal_with_t... |
"""
Script for performing a fit to a histogramm of recorded
time differences for the use with QNet
"""
from __future__ import print_function
import sys
from matplotlib import pylab
import numpy
import scipy.optimize as optimize
def fit(bincontent=None, binning=(0, 10, 21), fitrange=None):
"""
Fit function
... |
from easydict import EasyDict
pong_dqn_gail_config = dict(
exp_name='pong_gail_dqn_seed0',
env=dict(
collector_env_num=8,
evaluator_env_num=8,
n_evaluator_episode=8,
stop_value=20,
env_id='PongNoFrameskip-v4',
frame_stack=4,
),
reward_model=dict(
... |
class MyClass:
def method1(self):
print('myClass method1')
def method2(self, someString):
print("myclass method2 " + someString)
class MyOtherClass(MyClass):
def method1(self):
MyClass.method1(self)
print("anotherClass method1")
def main():
c = MyClass()
c.method... |
# WikiBot
#
# Made by Aryan Takalkar
import speech_recognition as speech
import wikipedia
import pyttsx3
engine = pyttsx3.init()
running = True
def speech_init():
engine.setProperty('rate', 175)
engine.setProperty('volume' , 2)
voices = engine.getPropertyvoices = engine.getProperty('v... |
"""
Provides utility functions for creating plots in exercise 8.
"""
from typing import Union
def organize_kwargs(
user_kwargs: Union[dict, None], default_kwargs: dict = None
) -> dict:
"""
Update default keyword argument configuration with user provided
configuration.
Parameters
----------
... |
import s3fs
import numpy as np
import pandas as pd
import xarray as xr
from pyproj import Proj
def isin_merra_cell(lat, lon, latm, lonm):
dlat, dlon = 0.5, 0.625
lat1, lat2 = latm - dlat/2, latm + dlat/2
lon1, lon2 = lonm - dlon/2, lonm + dlon/2
lon_slices = [(lon1, lon2)]
if lon2 > 180:
lo... |
"""Sets (expansions) information
"""
import datetime
from typing import Hashable
from . import utils
class Set(utils.i18nMixin, utils.NamedMixin):
"""A class representing a V:tES Set (expansion)."""
def __init__(self, **kwargs):
super().__init__()
self.id = 0
self.abbrev = kwargs.get... |
from SimPEG import *
import simpegEM as EM
from scipy.constants import mu_0
import matplotlib.pyplot as plt
plotIt = False
cs, ncx, ncz, npad = 5., 25, 15, 15
hx = [(cs,ncx), (cs,npad,1.3)]
hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)]
mesh = Mesh.CylMesh([hx,1,hz], '00C')
active = mesh.vectorCCz<0.
layer = (mesh.v... |
"""
Support for EnOcean sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.enocean/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, CONF_ID)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Yanis Guenane <yanis+ansible@guenane.org>
# Copyright (c) 2019, René Moser <mail@renemoser.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_functio... |
# Ensomniac 2022 Ryan Martin, ryan@ensomniac.com
# Andrew Stet, stetandrew@gmail.com
import os
import sys
class GlobalSpacing:
group: bool
ignore: str
source_code: list
iter_limit_range: range
starts_with_keyword: str
line_break_quantity: int
GetIndentSpaceCount: callable
... |
import cvxpy as cp
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils import check_X_y
from sklearn.metrics.pairwise import euclidean_distances
from wdwd.utils import pm1
from wdwd.linear_model import LinearClassifierMixin
class DWD(BaseEstimator, LinearClassifierMixin):
def __init__(... |
from psyrun import Param
pspace = Param()
python = 'true'
def execute():
return {}
|
import numpy as np
def PlotPlanetXZ(fig,R=1.0,Center=[0.0,0.0,0.0],zorder=10,NoBlack=False,NoonTop=True):
a = 2*np.pi*np.arange(361,dtype='float32')/360
x = R*np.sin(a) + Center[0]
z = R*np.cos(a) + Center[2]
if NoonTop:
fig.fill(z,x,color=[1.0,1.0,1.0],zorder=zorder)
fig.plot(z,x,color=[0,0,0],zorder=zo... |
def text(result):
output = [
f"active rolls: {result['active_rolls']}",
f"cycles: {result['cycles']}",
"",
]
for key in ["bakes", "endorsements", "total"]:
output.append(key)
col1 = "mean"
col2 = "max"
header = " " * 10 + f"{col1:>10} {col2:>10}"
... |
from app.runner.setup import setup
app = setup()
|
import os
from datetime import datetime, timezone
from typing import Dict
import click
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
class Config:
@property
def repository(self) -> str:
return os.getenv("GITHUB_REPOSITORY")
@property
def actor(self) -> str:
... |
import peewee
db = peewee.SqliteDatabase('./apidocs/api_doc.db')
class ApiDoc(peewee.Model):
title = peewee.CharField(default='')
url = peewee.CharField()
method = peewee.CharField()
description = peewee.CharField(default='')
class Meta:
database = db
|
# -*- coding:utf-8 -*-
import peewee
from torcms.core import tools
from torcms.model.core_tab import TabPost
from torcms.model.core_tab import TabRel
from torcms.model.core_tab import TabPost2Tag
from torcms.model.post2catalog_model import MPost2Catalog as MInfor2Catalog
from torcms.model.abc_model import Mabc
class... |
#!/usr/bin/env python3
import torch
from ..distributions import MultivariateNormal
from ..lazy import InterpolatedLazyTensor
from ..utils.broadcasting import _mul_broadcast_shape
from ..utils.interpolation import Interpolation, left_interp
from ..utils.memoize import cached
from ._variational_strategy import _Variati... |
from machine import Pin
import utime
#import pyb
class IRQCounter:
provides = ["count", "time_since_last_trigger"]
def __init__(self, port, trigger, cooldown):
self.counter = 0
self.last_trigger = utime.ticks_ms()
def irq_handler(pin):
now = utime.ticks_ms()
i... |
from __future__ import print_function, division, absolute_import, unicode_literals
from builtins import bytes, dict, object, range, map, input, str
from future.utils import itervalues, viewitems, iteritems, listvalues, listitems
from io import open
import pytest
import rfpipe
from astropy import time
def test_create... |
'''
* Copyright (c) 2022 MouBieCat
*
* 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, merge, publish, dist... |
from setuptools import setup
setup(
name="azblob",
version="1.0.1",
author="Philipp Lang",
packages=["azblob"],
url=("https://github.com/plang85/azblob"),
license="MIT License",
description="Download Azure blobs.",
long_description=open("README.md").read(),
long_description_content... |
# program to create set difference.
setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
setz = setx & sety
print(setz)
#Set difference
setb = setx - setz
print(setb) |
#!/usr/bin/env python
# coding: utf-8
# #NUMBER 1: DATA PREPARATION
# In[4]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
print("Done importing libraries")
# In[5]:
#path_to_file= "C:... |
import util
from copy import deepcopy
from collections import defaultdict
def solver(paticipants, pizas):
pizas_key = defaultdict(list)
for i, v in enumerate(pizas):
pizas_key[v].append(i)
acc = [[], 0]
print('File loaded :: size of piza : %s, paticipants : %d ' % (len(pizas), paticipants))
d... |
"""
[LeetCode] 708. Insert into a Cyclic Sorted List
# Insert into a Cyclic Sorted List linspiration
Problem
Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any ... |
# Estadística para Datos Univariados
Datos univariados (o data univariada) son datos que se describen con una sola variable. Por ejemplo, las alturas de los compñaeros de clase son datos univariados. El propósito principal del análisis de datos univariados es la descripción de los datos.
El análisis de datos univari... |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase
class WhoCommand(ModuleData, Command):
implements(IPlugin, I... |
"""Abstractions for handling operations with reaktor `WishList` and `Voucher` (`GiftCards`) objects."""
|
#! /usr/bin/env python3
# -*- coding: utf8 -*-
"""Port of NeHe Lesson 26 by Ivan Izuver <izuver@users.sourceforge.net>"""
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import sys
import gc
ESCAPE = b'\033'
# Number of the glut window.
window = 0
LightAmb = (0.7, 0... |
import functools
import queue
try:
import statistics
stdev = statistics.stdev
mean = statistics.mean
except ImportError:
stdev = None
def mean(l):
return sum(l) / len(l)
try:
import time
clock = time.perf_counter
except Exception:
import timeit
clock = timeit.default_time... |
from output.models.nist_data.atomic.non_negative_integer.schema_instance.nistschema_sv_iv_atomic_non_negative_integer_pattern_3_xsd.nistschema_sv_iv_atomic_non_negative_integer_pattern_3 import NistschemaSvIvAtomicNonNegativeIntegerPattern3
__all__ = [
"NistschemaSvIvAtomicNonNegativeIntegerPattern3",
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MybankCreditLoantradeNewloanarRepayApplyModel(object):
def __init__(self):
self._apply_repay_fee = None
self._apply_repay_int = None
self._apply_repay_penalty = None
... |
"""
# Syntax of search templates
"""
import re
# SYNTACTIC ANALYSIS OF SEARCH TEMPLATE ###
QWHERE = "/where/"
QHAVE = "/have/"
QWITHOUT = "/without/"
QWITH = "/with/"
QOR = "/or/"
QEND = "/-/"
QINIT = {QWHERE, QWITHOUT, QWITH}
QCONT = {QHAVE, QOR}
QTERM = {QEND}
PARENT_REF = ".."
ESCAPES = (
"\\\\",
"\\ "... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch
from . import Fairse... |
#! /usr/bin/env python3
import client
import common
import start
if __name__ == '__main__':
start.check_dirs()
common.w.replace_windows(*start.get_windows())
common.w.curses = True
config = start.read_config()
colour = start.validate_config(config)
if colour:
start.set_colours(config[... |
from unittest import TestCase
import string
from assertions import assert_result
from analyzer.predefined_recognizers.iban_recognizer import IbanRecognizer, IBAN_GENERIC_SCORE, LETTERS
from analyzer.entity_recognizer import EntityRecognizer
iban_recognizer = IbanRecognizer()
entities = ["IBAN_CODE"]
def update_iban_... |
"""
Define the list of possible commands that TeX might handle. These commands
might be composed of multiple instructions, such as 'input', which requires
characters forming a file-name as an argument.
"""
from enum import Enum
class Commands(Enum):
assign = 'ASSIGN'
relax = 'RELAX'
left_brace = 'LEFT_BRA... |
aluno = dict()
nome = str(input('Nome: '))
media = float(input('Média: '))
aluno['nome'] = nome
aluno['media'] = media
if media < 5:
aluno['status'] = 'Reprovado!'
elif 5 <= media < 7:
aluno['status'] = 'Recuperação!'
else:
aluno['status'] = 'Aprovado!'
print(f'Nome: {aluno["nome"]}.')
print(f'Média: {aluno["m... |
import config
config.setup_examples()
import infermedica_api
if __name__ == '__main__':
api = infermedica_api.get_api()
print('Look for evidences containing phrase headache:')
print(api.search('headache'), end="\n\n")
print('Look for evidences containing phrase breast, only for female specific symp... |
from flask import Flask, request, jsonify, redirect, url_for
import pyexcel.ext.xlsx
import pandas as pd
from werkzeug import secure_filename
UPLOAD_FOLDER = 'upload'
ALLOWED_EXTENSIONS = set(['xlsx'])
app=Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in fil... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import rasa_core
from rasa_core.agent import Agent
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import Memoi... |
import abc
from collections import namedtuple, OrderedDict
from typing import Collection, Optional, Union, Iterable, Tuple, Generator, Set, Dict, List, Any, Callable
from profilehooks import timecall
import logging
import itertools
import random
from .actions import pass_actions, tichu_actions, no_tichu_actions, pl... |
#!/usr/bin/python
import heat as h
dir='trace-azure-globe-6dc-24h-202005170045-202005180045'
src_dc_l = ['eastus2']
dst_dc_l = ['westus2', 'francecentral', 'australiaeast']
for src in src_dc_l:
for dst in dst_dc_l:
if dst is src:
continue
df=dir+'/' + src+'-'+dst+'.log.txt'
print df
##h.lat_he... |
# Time: O(s*t) # for every node in s, you traverse every node in t.
# Space: O(s) # number of nodes in s
# Mar 30th '20
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubtree(s... |
#!/usr/bin/python
# coding=utf-8
import logging
import itertools
import rdflib
# Import NameSpace RDF
from rdflib.namespace import RDF
from rdflib import Literal
# Import Namespace class for create new RDF Graph
from rdflib import Namespace
logging.basicConfig()
rdf = rdflib.Graph()
rdf.load("data.owl")
FOAF = Na... |
import django
from ..base import *
from ..i18n import *
from .services import *
from ..static import *
django.setup() |
import os
import json
import StringIO
import shapely
from shapely.geometry import shape, mapping
from flask import Flask, request, send_file, jsonify, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['js', 'json', 'geojson'])
app = Flask(__name__)
def allowed_file(filename):
ret... |
'''
Author: Hanqing Zhu(hqzhu@utexas.edu)
Date: 2022-04-07 10:38:34
LastEditTime: 2022-04-08 23:57:19
LastEditors: Hanqing Zhu(hqzhu@utexas.edu)
Description:
FilePath: /projects/ELight/core/models/__init__.py
'''
from .vgg import * |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from datetime import datetime
#from suit.widgets import SuitDateWidget, SuitTimeWidget, SuitSplitDateTimeWidget
#from .models import PrintTask
class TaskForm(forms.ModelForm):
... |
from __future__ import absolute_import
import warnings
from django.template import loader
from django.utils import six
from .. import compat
from . import filterset, filters
class DjangoFilterBackend(object):
default_filter_set = filterset.FilterSet
@property
def template(self):
if compat.is_c... |
from .rawheader import HeaderFactory, LAS_FILE_SIGNATURE
|
testinfra_hosts = ["ansible://mariadb-centos7"]
def test_mariadb_el7_config(host):
innodb7 = host.file('/etc/my.cnf.d/innodb.cnf')
assert not innodb7.contains('innodb_large_prefix=1')
testinfra_hosts = ["ansible://mariadb-centos8"]
def test_mariadb_el8_config(host):
innodb8 = host.file('/etc/my.cnf.d/... |
import requests
from .okra_base import OkraBase
from .utils import validate_id, validate_dates, validate_date_id
class Balance(OkraBase):
""" This handles all balance requests to the okra API. This contains the following functions.\n
Key functions:
get_balances -- This returns the realtime balance for e... |
# Import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from warmUpExercise import warmUpExercise
from computeCost import computeCost
from gradientDescent import gradientDescent
from plotData import plotData
# Machine Learning Online Class - Exercise 1:... |
# Generate the randomized beta map for further testing changes of prediction accuracy and discrimination
from os.path import join as pjoin
import cifti
import numpy as np
from ATT.iofunc import iofiles
def randomize_ROI(rawdata, mask=None):
"""
Randomize the averaged data in ROI that defined by the mask
i... |
from discord.ext import commands
from .formats import plural
class StringMaxLengthConverter(commands.Converter):
"""A converter that only accepts strings under a certain length."""
def __init__(self, length):
super().__init__()
self.length = length
async def convert(self, ctx, arg):
... |
# Generated by Django 3.1.8 on 2021-06-08 17:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sections', '0003_delete_techstack'),
]
operations = [
migrations.CreateModel(
name='TechStack',... |
import cv2 as cv
import numpy as np
import numpy.ma as ma
import scipy.interpolate
from scipy.interpolate import Akima1DInterpolator
def findTransform(fn):
pattern_size = (15,8)
trg_img_size = (1920, 1080)
scale_fact = 10 # to speed up calculations
print('processing %s... ' % fn)
orig = cv.... |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
import random
import time
try:
import thread
except ImportError:
import _thread as thread
import board
import neopixel
from gpiozero import Button
import json
import requests
import websocket
pixels = neopixel.NeoPixel(board.D18, 60+13, auto_write=False)
#0-60:tape, 6... |
# -*- 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 o... |
"""Elabore um programa que calcule o valor a ser pago por um produto,
considerando o seu preço normal e condição de pagamento:
- a vista dinheiro/cheque: 10% de desconto
- em até 2x no cartão: preco normal
- 3x ou mais no cartão: 20% de juros
"""
import time
print('========== Calculando Valores de Um Produto ==========... |
from django.contrib.gis import admin
from vida.vida.models import Person, Shelter, Track, Form, Report, Note, Profile
import uuid
import helpers
from django.conf import settings
class VidaAdmin(admin.OSMGeoAdmin):
openlayers_url = settings.STATIC_URL + 'openlayers/OpenLayers.js'
class NoteInline(admin.StackedIn... |
# 혁진이의 프로그램 검증
# DFS를 이용한 풀이
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV4yLUiKDUoDFAUx&categoryId=AV4yLUiKDUoDFAUx&categoryType=CODE
import sys
sys.setrecursionlimit(10**9)
def dfs(x, y, dir, cur):
global r, c
stat=False
rot=False
if cmd[x][y]=='>':
dir=... |
def add():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x+y
print("Your final result is: ", z)
def multiply():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x*y
print("Your final result is: ", z)
def factorial():
a=int(input())
f=1
if(a>1):
fo... |
from typing import NewType
from pydantic import SecretStr
from mirumon.api.api_model import APIModel
SharedKey = NewType("SharedKey", SecretStr)
class CreateDeviceBySharedKeyRequest(APIModel):
name: str
shared_key: SharedKey
|
# Flask imports
from flask import Blueprint, render_template
errors_blueprint = Blueprint('errors_blueprint', __name__)
@errors_blueprint.app_errorhandler(404)
def page_not_found(error):
return render_template('error_pages/404.html'), 404
@errors_blueprint.app_errorhandler(500)
def internal_server_error(error):... |
"""empty message
Revision ID: e47fb2d3a756
Revises:
Create Date: 2017-06-30 17:30:56.066364
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e47fb2d3a756'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.